Home > Article > Backend Development > Automatic memory management technology in C++ memory management
Automatic memory management technology in C is used to automatically allocate and release memory, including: smart pointers: std::shared_ptr: shared ownership pointer, automatically releasing memory. std::unique_ptr: Exclusive ownership pointer, the memory is automatically released after the variable goes out of scope. Container: std::vector: dynamically resized array, automatically releasing elements when out of range. std::map: Associative container, automatically releases all key-value pairs when out of scope.
Introduction
Memory management is crucial in C. Automatic memory management technology enables programmers to allocate and release memory without manual release.
Smart pointer
Container
Practical case
Use std::shared_ptr to manage objects:
#include <memory> class MyClass { /* ... */ }; int main() { std::shared_ptr<MyClass> ptr1(new MyClass()); std::shared_ptr<MyClass> ptr2 = ptr1; // 共享所有权 ptr1.reset(); // 设置 ptr1 为 nullptr,减少引用计数 if (ptr2) { // 检查 ptr2 是否有效 // 可以访问 MyClass 的内容 } return 0; }
Use std::unique_ptr to manage Resources:
#include <memory> class Resource { /* ... */ }; int main() { std::unique_ptr<Resource> res(new Resource()); // 使用 res // 变量 res 超出范围时,Resource 对象将自动释放 }
Use std::vector to store objects:
#include <vector> int main() { std::vector<int> numbers; numbers.push_back(1); numbers.push_back(2); numbers.push_back(3); // 访问 vector 中的元素 // 当 vector 超出范围时,所有元素都会自动释放 }
The above is the detailed content of Automatic memory management technology in C++ memory management. For more information, please follow other related articles on the PHP Chinese website!