C++ The smart pointer mechanism is a mechanism that automatically manages pointers to heap memory to prevent memory leaks and dangling pointers. Mainly including unique_ptr (unique ownership), shared_ptr (shared ownership) and weak_ptr (weak reference). It provides functions such as automatically releasing memory and checking pointer validity, simplifying memory management and improving code security.
C++ smart pointer mechanism
Introduction
C++ smart pointer is a A mechanism that automatically manages pointers to heap memory to simplify memory management and prevent problems such as memory leaks and dangling pointers. Smart pointers encapsulate raw pointers and provide additional functionality, such as automatically releasing memory and checking pointer validity.
Key concepts
Implementation
#include <memory> // 使用 unique_ptr std::unique_ptr<int> uptr = std::make_unique<int>(10); *uptr = 20; // 使用 shared_ptr std::shared_ptr<std::vector<int>> sptr = std::make_shared<std::vector<int>>(); sptr->push_back(1); sptr->push_back(2); // 使用 weak_ptr std::weak_ptr<int> wptr(uptr); if (auto sptr2 = wptr.lock()) { *sptr2 = 30; }
Practical case
Example 1: Preventing memory leaks
The following code uses raw pointers to manage dynamically allocated memory. If you accidentally release memory manually, a memory leak can occur.
int* ptr = new int(10); // ... delete ptr; // 必须记住释放内存
Using smart pointers can prevent this problem:
std::unique_ptr<int> uptr = std::make_unique<int>(10); // ... // uptr 会自动在析构时释放内存
Example 2: Shared Ownership
Consider the following situation, both functions use the same A dynamically allocated string. Raw pointers do not allow shared ownership, which can lead to program errors:
char* strPtr = new char[100]; void func1() { // 使用 strPtr } void func2() { // 也使用 strPtr }
Using shared_ptr can solve this problem:
std::shared_ptr<char[]> strPtr = std::make_shared<char[]>(100); void func1() { // 使用 strPtr } void func2() { // 也使用 strPtr }
Advantages
The above is the detailed content of Revealing the secret of C++ smart pointer mechanism to efficiently manage memory. For more information, please follow other related articles on the PHP Chinese website!