Detailed explanation of smart pointers in C + +

  • Share this:
post-title
Smart pointers in C + + are a mechanism for automatically managing dynamic memory, which can prevent memory leaks and handle the automatic release of resources. In C + +, we usually use std:: unique _ ptr and std:: shared _ ptr to implement the function of smart pointers. Std:: unique _ ptr is an rvalue reference type that takes ownership and automatically deletes the object it points to when its destructor is called. And std:: shared _ ptr has multiple owners, and when one of the owners leaves the scope, the object it points to is automatically deleted. By using smart pointers, we can effectively manage dynamically allocated memory and avoid memory leaks. At the same time, when an object is no longer needed, the smart pointer will automatically release the memory of the object without manual release.
In C + + programming, memory management is a crucial part.

As program complexity increases, manually managing dynamic memory becomes extremely difficult and error-prone.

To solve these problems, C + + 11 introduced smart pointers, which help developers avoid memory leaks and other resource management problems by automatically managing dynamic memory.

This article will detail two commonly used smart pointers: std::unique_ptrSumstd::shared_ptr, and shows how to use them to prevent memory leaks and handle the automatic release of resources.

What is a smart pointer?.

Smart pointers are a template class provided by the C + + standard library to automatically manage the life cycle of dynamically allocated objects.

They encapsulate the original pointer and automatically release the managed memory when appropriate.

Common smart pointers include std::unique_ptrstd::shared_ptrSumstd::weak_ptr

std::unique_ptrDetailed.

std::unique_ptrIs an exclusive smart pointer, meaning that there can only be one at a time std::unique_ptrThe instance owns an object.

It is suitable for scenarios where shared ownership is not required.

\n#

Basic usage.

pp
#include 
#include 

class MyClass {
public:
    MyClass() { std::cout << "MyClass Constructor\n"; }
    ~MyClass() { std::cout << "MyClass Destructor\n"; }
};

int main() {
    // 创建一个std::unique_ptr实例,管理一个MyClass对象
    std::unique_ptr ptr = std::make_unique();

    // 使用箭头操作符访问成员函数
    ptr->someMemberFunction();

    // 当ptr超出作用域时,MyClass对象会被自动销毁
    return 0;
}

In the above example, when ptrWhen out of scope, MyClassThe destructor of the object is called to free memory.

\n#

Transfer ownership.

std::unique_ptrCopying is not allowed, but can be done by std::moveTransfer ownership.

pp
std::unique_ptr createUniquePtr() {
    return std::make_unique();
}

int main() {
    std::unique_ptr ptr1 = createUniquePtr();
    std::unique_ptr ptr2 = std::move(ptr1); // 转移所有权

    // 现在ptr1不再拥有对象,ptr2拥有该对象
    return 0;
}

std::shared_ptrDetailed.

std::shared_ptrIs a shared ownership smart pointer that allows multiple std::shared_ptrInstances share the same object.

When the last std::shared_ptrWhen destroyed, the managed object will be released.

\n#

Basic usage.

pp
#include 
#include 

class MyClass {
public:
    MyClass() { std::cout << "MyClass Constructor\n"; }
    ~MyClass() { std::cout << "MyClass Destructor\n"; }
};

int main() {
    // 创建两个std::shared_ptr实例,管理同一个MyClass对象
    std::shared_ptr ptr1 = std::make_shared();
    std::shared_ptr ptr2 = ptr1; // 共享所有权

    // 使用箭头操作符访问成员函数
    ptr1->someMemberFunction();
    ptr2->someMemberFunction();

    // 当所有std::shared_ptr实例都超出作用域时,MyClass对象会被自动销毁
    return 0;
}

In the above example, even if ptr1Sumptr2Are out of scope, MyClassObjects will also not be destroyed until the last one std::shared_ptrInstances were also destroyed.

\n#

Circular reference problem.

std::shared_ptrIt may cause circular reference problems, that is, two or more objects hold each other's std::shared_ptr, resulting in memory not being properly released.

To solve this problem, you can use std::weak_ptr

pp
#include 
#include 

class B; // 前向声明

class A {
public:
    std::shared_ptr b_ptr;
    ~A() { std::cout << "A Destructor\n"; }
};

class B {
public:
    std::weak_ptr a_ptr; // 使用weak_ptr打破循环引用
    ~B() { std::cout << "B Destructor\n"; }
};

int main() {
    std::shared_ptr a = std::make_shared();
    std::shared_ptr b = std::make_shared();
    a->b_ptr = b;
    b->a_ptr = a; // 这里使用weak_ptr避免循环引用

    return 0;
}

In this example, ASumBHold each other std::shared_ptr, but by using std::weak_ptr, We avoid the circular reference problem.

WhenaSumbWhen out of scope, their destructor is called to properly free memory.

Summarize.

Smart pointers are indispensable tools in modern C + + programming. They greatly simplify memory management and reduce the risk of memory leaks.

std::unique_ptrFor exclusive ownership scenarios, while std::shared_ptrIt is suitable for scenarios that require shared ownership.

By using these smart pointers wisely, we can write more robustly and efficiently code.