Home >Backend Development >C++ >When is allocated memory freed in C++?
In C++, you need to free allocated memory to avoid memory leaks. Key opportunities to release memory include: when the scope ends (automatic release). Use smart pointers (auto-release). Explicitly free (using delete or delete[]).
#When is allocated memory released in C++?
In C++, you are responsible for freeing allocated memory. Failure to free memory can lead to memory leaks, which can degrade application performance and eventually lead to crashes. Here are a few key rules for deciding when to release memory:
1. When the scope ends:
{ int* ptr = new int; // ... } // ptr wird hier automatisch freigegeben
2. Use smart pointers:
std::unique_ptr
and std::shared_ptr
) automatically free memory when the object goes out of scope or the pointer is no longer needed. std::unique_ptr<int> ptr = std::make_unique<int>(); // ...
3. Explicit release:
delete
or delete[]
operator. int* ptr = new int; // ... delete ptr;
Practical case:
Consider the following example of allocating a dynamic array:
int* ptr = new int[10];
In this In the example, ptr
points to an array allocated 10 integers. After you are done using the array, you must free it. You can use the following methods:
delete[] ptr; // 显式释放数组
or use smart pointers:
std::unique_ptr<int[]> ptr(new int[10]); // 使用智能指针自动释放数组
The above is the detailed content of When is allocated memory freed in C++?. For more information, please follow other related articles on the PHP Chinese website!