UPDATE
这个答案相当古老,因此描述了当时“好的”,即 Boost 库提供的智能指针。从 C++11 开始,标准库已经提供了足够的智能指针类型,因此您应该倾向于使用std::unique_ptr, std::shared_ptr and 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++ 指针的类,用于管理所指向对象的生命周期。没有单一的智能指针类型,但它们都尝试以实用的方式抽象原始指针。
智能指针应该优先于原始指针。如果您觉得需要使用指针(首先考虑您是否reallydo),您通常会希望使用智能指针,因为这可以缓解原始指针的许多问题,主要是忘记删除对象和泄漏内存。
使用原始指针,程序员必须在对象不再有用时显式销毁该对象。
// 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 or 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
实例无法复制。这可以防止指针被多次(错误地)删除。但是,您可以将对它的引用传递给您调用的其他函数。
std::unique_ptr
当您想要将对象的生命周期绑定到特定的代码块时,或者如果您将其作为成员数据嵌入到另一个对象中(即另一个对象的生命周期)时,s 非常有用。该对象一直存在,直到包含的代码块退出,或者直到包含的对象本身被销毁。
更复杂的智能指针策略涉及指针的引用计数。这确实允许复制指针。当对该对象的最后一个“引用”被销毁时,该对象就被删除。该政策的实施由boost::shared_ptr and 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
定义对 a 的弱(不可计数)引用shared_ptr
.