什么是智能指针,我应该什么时候使用? [英] What is a smart pointer and when should I use one?

查看:122
本文介绍了什么是智能指针,我应该什么时候使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是智能指针,什么时候应该使用?

What is a smart pointer and when should I use one?

推荐答案

智能指针是一个类,原始(或裸)C ++指针,以管理指向的对象的生命周期。没有单一的智能指针类型,但是他们都试图以实用的方式抽象一个原始指针。

A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way.

智能指针应该优先于原始指针。如果你觉得你需要使用指针(首先考虑如果你真的),你通常会使用智能指针,因为这可以减轻许多原始指针的问题,主要是忘记删除对象和泄漏内存。

Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you really do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory.

使用原始指针,程序员必须显式销毁对象,当它不再有用。

With raw pointers, the programmer has to explicitly destroy the object when it is no longer useful.

// 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...?

比较的智能指针定义了对象何时被销毁的策略。您仍然必须创建对象,但是您不再需要担心破坏它。

A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it.

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


b $ b

使用的最简单的策略涉及智能指针包装器对象的范围,例如通过 boost :: scoped_ptr std :: unique_ptr

void f()
{
    {
       boost::scoped_ptr<MyObject> ptr(new MyObject());
       ptr->DoSomethingUseful();
    } // boost::scopted_ptr goes out of scope -- 
      // the MyObject is automatically destroyed.

    // ptr->Oops(); // Compile error: "ptr" not defined
                    // since it is no longer in scope.
}

注意 scoped_ptr 实例无法复制。这防止指针被多次删除(不正确)。

Note that scoped_ptr instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call.

当你想将对象的生命周期绑定到一个特定的块时,代码,或者如果将它作为成员数据嵌入到另一个对象中,那么该另一个对象的生命周期。对象存在,直到包含的代码块退出,或直到包含对象本身被销毁。

Scoped pointers are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed.

更复杂的智能指针策略涉及引用计数指针。这允许复制指针。当对象的最后一个引用被销毁时,对象被删除。此政策由 boost :: shared_ptr std :: shared_ptr

A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last "reference" to the object is destroyed, the object is deleted. This policy is implemented by 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.

引用计数指针在对象的生命周期复杂得多,

Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object.

引用计数指针有一个缺点 - 创建悬挂引用的可能性:

There is one drawback to reference counted pointers — the possibility of creating a dangling reference:

// 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!

另一种可能性是创建循环引用:

Another possibility is creating circular references:

struct Owner {
   boost::shared_ptr<Owner> other;
};

boost::shared_ptr<Owner> p1 (new Owner());
boost::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 的弱(未计数)引用。

To work around this problem, both Boost and C++11 have defined a weak_ptr to define a weak (uncounted) reference to a shared_ptr.

这个答案比较陈旧,所以描述了当时的好,这是Boost库提供的智能指针。由于C ++ 11,标准库提供了足够的智能指针类型,因此您应该倾向于使用 std :: unique_ptr std :: shared_ptr std :: weak_ptr

This answer is rather old, and so describes what was 'good' at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of std::unique_ptr, std::shared_ptr and std::weak_ptr.

还有 std: :auto_ptr 。它非常像一个范围指针,除了它也有特殊危险的能力,被复制 - 这也意外转移所有权! 它在最新的标准中已被弃用,因此您不应该使用它。请改用 std :: unique_ptr 。 / strong>

There is also std::auto_ptr. It is very much like a scoped pointer, except that it also has the "special" dangerous ability to be copied — which also unexpectedly transfers ownership! It is deprecated in the newest standards, so you shouldn't use it. Use the std::unique_ptr instead.

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.

这篇关于什么是智能指针,我应该什么时候使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆