📜  malloc()与C++中的新增功能(1)

📅  最后修改于: 2023-12-03 15:02:51.190000             🧑  作者: Mango

Introduction to Malloc() and New Features in C++
Malloc()

malloc() is a function in C programming language that helps in allocating memory dynamically during runtime. It is short for "memory allocation."

The syntax for using malloc() is:

ptr = (cast-type*) malloc(byte-size);

Here, ptr is a pointer of type cast-type. cast-type is the type of data to which the pointer points. And byte-size is the number of bytes to be allocated.

Example:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *ptr;
    int n = 5;
    ptr = (int*) malloc(n * sizeof(int));
    if (ptr == NULL) 
    {
        printf("Memory allocation failed!\n");
        exit(0);
    }
    else
    {
        printf("Memory allocation successful!\n");
        for (int i = 0; i < n; i++) 
        {
            ptr[i] = i + 1;
        }
        printf("Values stored in memory: ");
        for (int i = 0; i < n; i++) 
        {
            printf("%d ", ptr[i]);
        }
        printf("\n");
        free(ptr);
    }
    return 0;
}

Output:

Memory allocation successful!
Values stored in memory: 1 2 3 4 5 

malloc() is a useful function when you need to allocate memory dynamically during runtime. It is important to remember to free() the allocated memory after using it, or your program may end up with memory leaks.

New Features in C++

C++ has many new features that have been added in recent years that are worth mentioning. Here are a few:

Lambda Expressions

Lambda expressions are small, anonymous functions that can be used to simplify your code. They were introduced in C++11.

Here is an example:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> nums {1, 2, 3, 4, 5};
    std::for_each(nums.begin(), nums.end(), [](int n) { std::cout << n << " "; });
    return 0;
}

Output:

1 2 3 4 5 

Range-Based For Loops

Range-based for loops were also introduced in C++11. They make iterating through collections easier.

Here is an example:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> nums {1, 2, 3, 4, 5};
    for (auto n : nums) 
    {
        std::cout << n << " ";
    }
    return 0;
}

Output:

1 2 3 4 5 

nullptr

nullptr is a keyword in C++11 that is used in place of NULL. It is a type-safe alternative that can prevent some bugs when working with pointers.

Here is an example:

#include <iostream>

void foo(int n)
{
    std::cout << "foo(int)" << std::endl;
}

void foo(char* s)
{
    std::cout << "foo(char*)" << std::endl;
}

int main()
{
    foo(NULL);      // Will call foo(int)
    foo(nullptr);   // Will call foo(char*)
    return 0;
}

Output:

foo(int)
foo(char*)

Smart Pointers

C++11 introduced smart pointers, which are designed to automate the process of memory management. They come in three types: unique_ptr, shared_ptr, and weak_ptr.

Here is an example using unique_ptr:

#include <iostream>
#include <memory>

void foo(std::unique_ptr<int>& ptr)
{
    std::cout << "foo: " << *ptr << std::endl;
}

int main()
{
    std::unique_ptr<int> ptr(new int(42));
    foo(ptr);
    std::cout << "main: " << *ptr << std::endl;     // Will cause a runtime error
    return 0;
}

Output:

foo: 42

Note that trying to access the memory after passing the unique_ptr to the function will cause a runtime error. Smart pointers can be a powerful tool when used correctly, but it's important to understand how they work and when to use them.