How to manage memory in C++?

In C++, memory management is primarily done through the following methods:

New/delete operators are used for dynamically allocating and freeing memory. The new operator is used to allocate memory and return a pointer to that memory, while the delete operator is used to release dynamically allocated memory.

int* ptr = new int; // 分配int类型的内存
*ptr = 10; // 写入值
delete ptr; // 释放内存

2. In C++, you can also use the malloc and free functions from the C standard library for memory allocation and deallocation, but it is important to note that memory allocated using malloc needs to be released using free.

int* ptr = (int*)malloc(sizeof(int)); // 分配int类型的内存
*ptr = 10; // 写入值
free(ptr); // 释放内存

Option: Smart pointers were introduced in C++11, with the most commonly used being std::shared_ptr and std::unique_ptr. Smart pointers can automatically manage memory, prevent memory leaks, and release memory automatically when the scope ends.

std::shared_ptr<int> ptr = std::make_shared<int>(10); // 分配int类型的内存

4. RAII(Resource Acquisition Is Initialization): RAII is a programming technique where resources are acquired during object construction and released during object destruction to ensure proper resource management, avoiding memory leaks caused by forgetting to release resources.

class Resource {
    int* ptr;
    Resource() : ptr(new int) {}
    ~Resource() { delete ptr; }

The above are common memory management techniques in C++. Choose the appropriate method for managing memory in your project to ensure the correctness of memory allocation and deallocation.

Leave a Reply 0

Your email address will not be published. Required fields are marked *