什么是智能指针,什么时候应该使用?
当前回答
智能指针是那些你不必担心内存取消分配、资源共享和传输的地方。
您可以很好地使用这些指针,其方式与Java中的任何分配方式类似。在java垃圾收集器中完成了这一任务,而在智能指针中,这一任务由Destructor完成。
其他回答
什么是智能指针。
长版本,原则上:
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.
Chris、Sergdev和Llyod提供的定义是正确的。我更喜欢一个更简单的定义,只是为了让我的生活简单:智能指针只是一个重载->和*运算符的类。这意味着你的对象在语义上看起来像一个指针,但你可以让它做一些更酷的事情,包括引用计数、自动销毁等。sharedptr和autoptr在大多数情况下都是足够的,但它们也有自己的一些小特点。
更新:
对于过去使用的C++类型,这个答案已经过时了。std::auto_ptr在新标准中被弃用并删除。应该使用std::shared_ptr而不是boost::shared_pt,这是标准的一部分。
与智能指针原理背后的概念的联系仍然是最相关的。
现代C++具有以下智能指针类型,不需要boost智能指针:
std::shared_ptr标准::weak_ptr标准::unique_ptr
答案中还提到了该书的第二版:《C++模板:完整指南第二版》,作者:David Vandvoorde Nicolai、M.Josuttis、Douglas Gregor
旧答案:
智能指针是一种类似指针的类型,具有一些附加功能,例如自动内存释放、引用计数等。
智能指针页面上有一个小介绍-什么,为什么,哪个?。
其中一种简单的智能指针类型是std::auto_ptr(C++标准第20.4.5章),它允许在内存超出范围时自动释放内存,并且在抛出异常时比简单的指针用法更健壮,尽管灵活性较低。
另一种方便的类型是boost::shared_ptr,它实现引用计数,并在没有对对象的引用时自动释放内存。这有助于避免内存泄漏,并且易于用于实现RAII。
David Vandvoorde、Nicolai M.Josuttis的《C++模板:完整指南》一书第20章对这一主题进行了深入探讨。智能指针。涉及的一些主题:
防止异常Holders,(注意,std::auto_ptr是此类智能指针的实现)资源获取是初始化(这通常用于C++中的异常安全资源管理)持有人限制参考计数并发计数器访问销毁和处置
现有的答案很好,但不包括当智能指针不是您试图解决的问题的(完整)答案时该做什么。
除了其他事情(在其他答案中解释得很好)之外,使用智能指针是如何将抽象类用作函数返回类型的一个可能的解决方案?该问题被标记为该问题的副本。然而,如果想在C++中指定抽象(或实际上任何)基类作为返回类型,首先要问的问题是“你真正的意思是什么?”。boost指针容器库的文档中对C++中惯用的面向对象编程(以及这与其他语言的区别)进行了很好的讨论(并提供了进一步的参考)。总之,在C++中,您必须考虑所有权。哪些智能指针可以帮助您,但不是唯一的解决方案,或者总是一个完整的解决方案(它们不会为您提供多态副本),也不总是您希望在接口中公开的解决方案。例如,返回引用就足够了。但是在所有这些情况下(智能指针、指针容器或简单地返回引用),您已经将返回从值更改为某种形式的引用。如果你真的需要复制,你可能需要添加更多的样板“习惯用法”,或者使用Adobe Poly或Boost.TypeErasure等库从C++中的惯用(或其他)OOP过渡到更通用的多态性。
让T成为本教程中的一个班级C++中的指针可以分为3种类型:
1) 原始指针:
T a;
T * _ptr = &a;
它们将内存地址保存到内存中的某个位置。小心使用,因为程序变得复杂,难以跟踪。
具有常量数据或地址的指针{向后读取}
T a ;
const T * ptr1 = &a ;
T const * ptr1 = &a ;
指向作为常量的数据类型T的指针。这意味着不能使用指针更改数据类型。ie*ptr1=19;不会起作用。但是你可以移动指针。即ptr1++、ptr1--;等等都会起作用。向后读取:指向类型T(常量)的指针
T * const ptr2 ;
指向数据类型T的常量指针。这意味着不能移动指针,但可以更改指针指向的值。ie*ptr2=19将工作,但ptr2++;ptr2等将不起作用。向后读取:指向T类型的常量指针
const T * const ptr3 ;
指向常量数据类型T的常量指针。这意味着您既不能移动指针,也不能将数据类型指针更改为指针。即。ptr3--;ptr3++*ptr3=19;不起作用
3) 智能指针:{#include<memory>}
共享指针:
T a ;
//shared_ptr<T> shptr(new T) ; not recommended but works
shared_ptr<T> shptr = make_shared<T>(); // faster + exception safe
std::cout << shptr.use_count() ; // 1 // gives the number of "
things " pointing to it.
T * temp = shptr.get(); // gives a pointer to object
// shared_pointer used like a regular pointer to call member functions
shptr->memFn();
(*shptr).memFn();
//
shptr.reset() ; // frees the object pointed to be the ptr
shptr = nullptr ; // frees the object
shptr = make_shared<T>() ; // frees the original object and points to new object
使用引用计数实现,以跟踪有多少“东西”指向指针指向的对象。当此计数为0时,对象将自动删除,即当指向对象的所有share_ptr超出范围时,对象被删除。这消除了必须删除使用new分配的对象的麻烦。
弱指针:帮助处理使用共享指针时出现的循环引用如果有两个对象被两个共享指针指向,并且有一个内部共享指针指向其他共享指针,则会有一个循环引用,当共享指针超出范围时,不会删除该对象。要解决此问题,请将内部成员从shared_ptr更改为weak_ptr。注意:要访问弱指针指向的元素,请使用lock(),这将返回一个weak_ptr。
T a ;
shared_ptr<T> shr = make_shared<T>() ;
weak_ptr<T> wk = shr ; // initialize a weak_ptr from a shared_ptr
wk.lock()->memFn() ; // use lock to get a shared_ptr
// ^^^ Can lead to exception if the shared ptr has gone out of scope
if(!wk.expired()) wk.lock()->memFn() ;
// Check if shared ptr has gone out of scope before access
请参见:std::weak_ptr何时有用?
唯一指针:拥有独家所有权的轻质智能指针。当指针指向唯一对象而不在指针之间共享对象时使用。
unique_ptr<T> uptr(new T);
uptr->memFn();
//T * ptr = uptr.release(); // uptr becomes null and object is pointed to by ptr
uptr.reset() ; // deletes the object pointed to by uptr
要更改唯一ptr指向的对象,请使用移动语义
unique_ptr<T> uptr1(new T);
unique_ptr<T> uptr2(new T);
uptr2 = std::move(uptr1);
// object pointed by uptr2 is deleted and
// object pointed by uptr1 is pointed to by uptr2
// uptr1 becomes null
参考文献:它们本质上可以被认为是常量指针,即常量指针,不能用更好的语法移动。
参见:C++中指针变量和引用变量之间的区别是什么?
r-value reference : reference to a temporary object
l-value reference : reference to an object whose address can be obtained
const reference : reference to a data type which is const and cannot be modified
参考:https://www.youtube.com/channel/UCEOGtxYTB6vo6MQ-WQ9W_nQ 感谢安德烈指出了这个问题。