什么是智能指针,什么时候应该使用?
当前回答
智能指针是那些你不必担心内存取消分配、资源共享和传输的地方。
您可以很好地使用这些指针,其方式与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.
http://en.wikipedia.org/wiki/Smart_pointer
在计算机科学中,智能指针是一种抽象数据类型模拟指针,同时提供其他功能,如自动垃圾收集或边界检查。这些附加功能旨在减少因误用指针,同时保持效率。智能指针通常跟踪指向它们的对象内存管理的目的。这个指针的误用是一个主要原因错误:恒定分配,释放和引用由编写的程序执行使用指针很可能会发生一些内存泄漏。智能指针试图阻止内存通过制造资源泄漏自动解除分配:当指向对象的指针(或一系列指针)被破坏例如,因为它超出了范围,指向的对象也被破坏。
智能指针类似于常规(类型化)指针,如“char*”,除非指针本身超出范围,否则它所指向的内容也会被删除。您可以像使用常规指针一样使用它,方法是使用“->”,但如果您需要指向数据的实际指针,则不需要。为此,可以使用“&*ptr”。
它适用于:
对象必须分配新的,但您希望与堆栈中的对象具有相同的生存期。如果对象被分配给智能指针,那么当程序退出该函数/块时,它们将被删除。类的数据成员,因此当对象被删除时,所有拥有的数据也会被删除,而析构函数中没有任何特殊代码(您需要确保析构函数是虚拟的,这几乎总是一件好事)。
在以下情况下,您可能不想使用智能指针:
…指针实际上不应该拥有数据。。。即,当您只是在使用数据,但希望它在引用它的函数中生存时。…智能指针本身不会在某个时刻被破坏。您不希望它位于永远不会被破坏的内存中(例如动态分配但不会显式删除的对象中)。…两个智能指针可能指向相同的数据。(然而,还有更聪明的指针可以处理这一点……这就是所谓的引用计数。)
另请参见:
垃圾收集。关于数据所有权的堆栈溢出问题
更新
这个答案相当陈旧,因此描述了当时的“好”,这是Boost库提供的智能指针。自C++11以来,标准库提供了足够的智能指针类型,因此您应该倾向于使用std::unique_ptr、std::shared_ptr和std::weak_ptr。
还有std::auto_ptr。它非常像一个作用域指针,只是它还具有“特殊”的危险复制能力——这也意外地转移了所有权。它在C++11中被弃用,在C++17中被删除,因此您不应该使用它。
std::auto_ptr<MyObject> p1 (new MyObject());
std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership.
// p1 gets set to empty!
p2->DoSomething(); // Works.
p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception.
旧答案
智能指针是一个包装“原始”(或“裸”)C++指针的类,用于管理所指向对象的生存期。没有单一的智能指针类型,但所有的智能指针都试图以实用的方式抽象原始指针。
智能指针应优先于原始指针。如果您觉得需要使用指针(如果确实需要,请首先考虑),通常会使用智能指针,因为这可以缓解原始指针的许多问题,主要是忘记删除对象和内存泄漏。
对于原始指针,程序员必须在对象不再有用时显式地销毁它。
// Need to create the object to achieve some goal
MyObject* ptr = new MyObject();
ptr->DoSomething(); // Use the object in some way
delete ptr; // Destroy the object. Done with it.
// Wait, what if DoSomething() raises an exception...?
通过比较,智能指针定义了有关对象何时被销毁的策略。您仍然需要创建对象,但不必再担心会破坏它。
SomeSmartPtr<MyObject> ptr(new MyObject());
ptr->DoSomething(); // Use the object in some way.
// Destruction of the object happens, depending
// on the policy the smart pointer class uses.
// Destruction would happen even if DoSomething()
// raises an exception
使用中最简单的策略涉及智能指针包装器对象的范围,例如通过boost::scoped_ptr或std::unique_ptr实现。
void f()
{
{
std::unique_ptr<MyObject> ptr(new MyObject());
ptr->DoSomethingUseful();
} // ptr goes out of scope --
// the MyObject is automatically destroyed.
// ptr->Oops(); // Compile error: "ptr" not defined
// since it is no longer in scope.
}
注意,不能复制std::unique_ptr实例。这可以防止指针被多次删除(错误地)。但是,您可以将对它的引用传递给您调用的其他函数。
当您想要将对象的生存期与特定的代码块绑定时,或者如果您将其作为成员数据嵌入到另一个对象中,那么uniqueptrs非常有用。该对象一直存在,直到包含代码块退出,或者直到包含对象本身被销毁。
更复杂的智能指针策略涉及对指针进行引用计数。这允许复制指针。当对象的最后一个“引用”被破坏时,该对象将被删除。此策略由boost::shared_ptr和std::shared-ptr实现。
void f()
{
typedef std::shared_ptr<MyObject> MyObjectPtr; // nice short alias
MyObjectPtr p1; // Empty
{
MyObjectPtr p2(new MyObject());
// There is now one "reference" to the created object
p1 = p2; // Copy the pointer.
// There are now two references to the object.
} // p2 is destroyed, leaving one reference to the object.
} // p1 is destroyed, leaving a reference count of zero.
// The object is deleted.
当对象的生存期复杂得多,并且不直接与特定的代码段或其他对象绑定时,引用计数指针非常有用。
引用计数指针有一个缺点——创建悬空引用的可能性:
// Create the smart pointer on the heap
MyObjectPtr* pp = new MyObjectPtr(new MyObject())
// Hmm, we forgot to destroy the smart pointer,
// because of that, the object is never destroyed!
另一种可能是创建循环引用:
struct Owner {
std::shared_ptr<Owner> other;
};
std::shared_ptr<Owner> p1 (new Owner());
std::shared_ptr<Owner> p2 (new Owner());
p1->other = p2; // p1 references p2
p2->other = p1; // p2 references p1
// Oops, the reference count of of p1 and p2 never goes to zero!
// The objects are never destroyed!
为了解决这个问题,Boost和C++11都定义了weak_ptr来定义对shared_ptr的弱(未计数)引用。
智能指针是一种类似指针的对象,但它还提供了对构造、销毁、复制、移动和取消引用的控制。
人们可以实现自己的智能指针,但许多库也提供智能指针实现,每个实现都有不同的优点和缺点。
例如,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中存在,但现在已弃用。
推荐文章
- 什么是“参数依赖查找”(又名ADL,或“Koenig查找”)?
- 公共朋友交换成员函数
- 如何在Go中使用c++
- 自定义c++分配器的引人注目的例子?
- RAII和c++中的智能指针
- 如何构建和使用谷歌TensorFlow c++ api
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 在STL地图中,使用map::insert比[]更好吗?
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Std::cin输入空格?
- c++标准是否要求iostreams的性能很差,或者我只是在处理一个糟糕的实现?
- gcc在哪里查找C和c++头文件?
- 为什么我们需要require require ?