c+智能指针源码分析
In this article, we’ll take a look at how we can use Smart Pointers in C++.
在本文中,我们将研究如何在C ++中使用智能指针 。
Smart Pointers are an abstract interface to actual pointers (also called raw pointers), but with the additional benefit of automatically managing resources and freeing memory.
智能指针是实际指针(也称为原始指针 )的抽象接口,但具有自动管理资源和释放内存的其他好处。
![Smart Ptr Example](https://cdn.journaldev.com/wp-content/uploads/2020/03/smart_ptr_example.png)
The design logic for a smart pointer is to implement it as a class.
智能指针的设计逻辑是将其实现为类。
This is because a class has a destructor, which will trigger automatically when an object is at the end of its scope. Smart Pointers use the destructors to free up resources automatically.
这是因为类具有析构函数 ,当对象位于其作用域的末尾时,它将自动触发。 智能指针使用析构函数自动释放资源。
You don’t need to free smart pointers explicitly, and hence they are “smart” pointers since they know when they need to free resources.
您无需显式释放智能指针,因此它们是“智能”指针,因为它们知道何时需要释放资源。
Let’s understand more about these types of smart pointers in C++, using examples.
通过示例,让我们更多地了解C ++中的这些智能指针类型。
在C ++中使用智能指针 (Using Smart Pointers in C++)
These pointers are defined in the standard C++ library, in the std
namespace. To include some of these pointers, we also need the <memory>
header file.
这些指针是在标准C ++库的std
名称空间中定义的。 要包括其中一些指针,我们还需要<memory>
头文件。
There are three commonly used smart pointers, called:
有三种常用的智能指针,称为:
- unique_ptr unique_ptr
- shared_ptr shared_ptr
- weak_ptr weak_ptr
Let’s go through them one by one.
让我们一一介绍。
unique_ptr – C ++中的智能指针 (unique_ptr – Smart pointer in C++)
This is a smart pointer that will only permit one owner of the pointer. That is, unique_ptr
can contain, at maximum, only a single raw pointer (“unique” pointer) that points to a single memory location.
这是一个智能指针,将只允许该指针的一个所有者。 也就是说, unique_ptr
最多只能包含一个指向单个内存位置的原始指针 (“唯一”指针)。
Keep this as your default choice, unless you’re working with multiple threads, or whenever you need multiple owners to the same raw pointer.
除非您正在使用多个线程,或者需要多个所有者使用同一原始指针,否则请将其保留为默认选择。
To create a smart pointer using unique_ptr, there are two ways of achieving this:
要使用unique_ptr创建智能指针,有两种方法可以实现:
情况1:从对象创建唯一的智能指针 (Case 1: Creating a Unique Smart Pointer from an object)
If you have an object and want to create a smart pointer in C++ which points to this object, use the below syntax:
如果您有一个对象,并且想要在C ++中创建指向该对象的智能指针&#