什么是智能指针,什么时候应该使用?
当前回答
Chris、Sergdev和Llyod提供的定义是正确的。我更喜欢一个更简单的定义,只是为了让我的生活简单:智能指针只是一个重载->和*运算符的类。这意味着你的对象在语义上看起来像一个指针,但你可以让它做一些更酷的事情,包括引用计数、自动销毁等。sharedptr和autoptr在大多数情况下都是足够的,但它们也有自己的一些小特点。
其他回答
智能指针是一个类,是普通指针的包装。与普通指针不同,智能指针的生命周期基于引用计数(智能指针对象被分配的次数)。因此,每当智能指针分配给另一个指针时,内部引用计数加上。每当对象超出范围时,引用计数减。
自动指针,虽然看起来类似,但与智能指针完全不同。这是一个方便的类,每当自动指针对象超出变量范围时,它就释放资源。在某种程度上,它使指针(指向动态分配的内存)的工作方式类似于堆栈变量(在编译时静态分配)。
智能指针是那些你不必担心内存取消分配、资源共享和传输的地方。
您可以很好地使用这些指针,其方式与Java中的任何分配方式类似。在java垃圾收集器中完成了这一任务,而在智能指针中,这一任务由Destructor完成。
Chris、Sergdev和Llyod提供的定义是正确的。我更喜欢一个更简单的定义,只是为了让我的生活简单:智能指针只是一个重载->和*运算符的类。这意味着你的对象在语义上看起来像一个指针,但你可以让它做一些更酷的事情,包括引用计数、自动销毁等。sharedptr和autoptr在大多数情况下都是足够的,但它们也有自己的一些小特点。
什么是智能指针。
长版本,原则上:
https://web.stanford.edu/class/archive/cs/cs106l/cs106l.1192/lectures/lecture15/15_RAII.pdf
现代C++习惯用法:
RAII: Resource Acquisition Is Initialization.
● When you initialize an object, it should already have
acquired any resources it needs (in the constructor).
● When an object goes out of scope, it should release every
resource it is using (using the destructor).
要点:
● There should never be a half-ready or half-dead object.
● When an object is created, it should be in a ready state.
● When an object goes out of scope, it should release its resources.
● The user shouldn’t have to do anything more.
原始指针违反RAII:当指针超出范围时,需要用户手动删除。
RAII解决方案为:
Have a smart pointer class:
● Allocates the memory when initialized
● Frees the memory when destructor is called
● Allows access to underlying pointer
对于需要复制和共享的智能指针,请使用shared_ptr:
● use another memory to store Reference counting and shared.
● increment when copy, decrement when destructor.
● delete memory when Reference counting is 0.
also delete memory that store Reference counting.
对于不拥有原始指针的智能指针,请使用weak_ptr:
● not change Reference counting.
shared_ptr用法:
correct way:
std::shared_ptr<T> t1 = std::make_shared<T>(TArgs);
std::shared_ptr<T> t2 = std::shared_ptr<T>(new T(Targs));
wrong way:
T* pt = new T(TArgs); // never exposure the raw pointer
shared_ptr<T> t1 = shared_ptr<T>(pt);
shared_ptr<T> t2 = shared_ptr<T>(pt);
始终避免使用原始指针。
对于必须使用原始指针的场景:
https://stackoverflow.com/a/19432062/2482283
对于非空指针的原始指针,请改用引用。
not use T*
use T&
对于可能为null的可选引用,请使用原始指针,这意味着:
T* pt; is optional reference and maybe nullptr.
Not own the raw pointer,
Raw pointer is managed by some one else.
I only know that the caller is sure it is not released now.
智能指针是一种类似指针的对象,但它还提供了对构造、销毁、复制、移动和取消引用的控制。
人们可以实现自己的智能指针,但许多库也提供智能指针实现,每个实现都有不同的优点和缺点。
例如,Boost提供了以下智能指针实现:
shared_ptr<T>是一个指向T的指针,它使用引用计数来确定何时不再需要对象。scoped_ptr<T>是一个在超出范围时自动删除的指针。无法分配。intrusive_ptr<T>是另一个引用计数指针。它提供了比shared_ptr更好的性能,但需要类型T提供自己的引用计数机制。weak_ptr<T>是一个弱指针,与shared_ptr一起工作以避免循环引用。shared_array<T>类似于shared_ptr,但对于T的数组。scoped_array<T>类似于scoped_ptr,但对于T的数组。
这些只是对每一个的一个线性描述,可以根据需要使用,有关更多细节和示例,可以查看Boost的文档。
此外,C++标准库提供了三个智能指针;std::unique_ptr表示唯一所有权,std::shared_ptr表示共享所有权,std::weak_ptr表示共享所有权。std::auto_ptr在C++03中存在,但现在已弃用。