C++ unique_ptr 和 shared_ptr 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6876751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:48:19  来源:igfitidea点击:

Differences between unique_ptr and shared_ptr

c++pointersc++11shared-ptrunique-ptr

提问by smallB

Possible Duplicates:
pimpl: shared_ptr or unique_ptr
smart pointers (boost) explained

可能的重复项:
pimpl:shared_ptr 或 unique_ptr
智能指针(boost)解释

Could someone explain differences between shared_ptr and unique_ptr?

有人可以解释 shared_ptr 和 unique_ptr 之间的区别吗?

回答by templatetypedef

Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type can refer to a resource.

这两个类都是智能指针,这意味着它们会自动(在大多数情况下)在无法再引用该对象时释放它们指向的对象。两者的区别在于每种类型有多少个不同的指针可以引用一个资源。

When using unique_ptr, there can be at most one unique_ptrpointing at any one resource. When that unique_ptris destroyed, the resource is automatically reclaimed. Because there can only be one unique_ptrto any resource, any attempt to make a copy of a unique_ptrwill cause a compile-time error. For example, this code is illegal:

使用时unique_ptr,最多可以有一个unique_ptr指向任何一种资源。当它unique_ptr被销毁时,资源会自动回收。因为unique_ptr任何资源只能有一个,所以任何尝试复制 aunique_ptr都会导致编译时错误。例如,这段代码是非法的:

unique_ptr<T> myPtr(new T);       // Okay
unique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr

However, unique_ptrcan be movedusing the new move semantics:

然而,unique_ptr移动使用新的移动语义:

unique_ptr<T> myPtr(new T);                  // Okay
unique_ptr<T> myOtherPtr = std::move(myPtr); // Okay, resource now stored in myOtherPtr

Similarly, you can do something like this:

同样,您可以执行以下操作:

unique_ptr<T> MyFunction() {
    unique_ptr<T> myPtr(/* ... */);

    /* ... */

    return myPtr;
}

This idiom means "I'm returning a managed resource to you. If you don't explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of unique_ptras a safer, better replacement for auto_ptr.

这个习语的意思是“我将一个托管资源返回给你。如果你没有明确捕获返回值,那么资源将被清理。如果你这样做了,那么你现在拥有该资源的独占所有权。” 通过这种方式,您可以unique_ptrauto_ptr.

shared_ptr, on the other hand, allows for multiple pointers to point at a given resource. When the very last shared_ptrto a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:

shared_ptr,另一方面,允许多个指针指向给定的资源。当最后shared_ptr一个资源被销毁时,该资源将被释放。例如,这段代码是完全合法的:

shared_ptr<T> myPtr(new T);       // Okay
shared_ptr<T> myOtherPtr = myPtr; // Sure!  Now have two pointers to the resource.

Internally, shared_ptruses reference countingto track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.

在内部,shared_ptr使用引用计数来跟踪引用资源的指针数量,因此您需要注意不要引入任何引用循环。

In short:

简而言之:

  1. Use unique_ptrwhen you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.
  2. Use shared_ptrwhen you want multiple pointers to the same resource.
  1. 使用unique_ptr时您需要一个指针时单指针被销毁,将被回收的对象。
  2. 使用shared_ptr时,你想多指向相同的资源。

Hope this helps!

希望这可以帮助!

回答by Kerrek SB

unique_ptris the light-weight smart pointer of choice if you just have a dynamic object somewhere for which oneconsumer has sole (hence "unique") responsibility -- maybe a wrapper class that needs to maintain some dynamically allocated object. unique_ptrhas very little overhead. It is not copyable, but movable. Its typeis template <typename D, typename Deleter> class unique_ptr;, so it depends on twotemplate parameters.

unique_ptr如果您在某处只有一个消费者对其负有唯一(因此“唯一”)责任的动态对象,那么它是首选的轻量级智能指针——可能是一个需要维护一些动态分配对象的包装类。unique_ptr有很少的开销。它不可复制,但可移动。它的类型template <typename D, typename Deleter> class unique_ptr;,所以它取决于两个模板参数。

unique_ptris also what auto_ptrwanted to be in the old C++ but couldn't because of that language's limitations.

unique_ptr也是auto_ptr旧 C++ 中想要的,但由于该语言的限制而无法使用。

shared_ptron the other hand is a very different animal. The obvious difference is that you can have many consumers sharing responsibility for a dynamic object (hence "shared"), and the object will only be destroyed when all shared pointers have gone away. Additionally you can have observing weak pointerswhich will intelligently be informed if the shared pointer they're following has disappeared.

shared_ptr另一方面是一种非常不同的动物。明显的区别是您可以让许多消费者共同负责一个动态对象(因此是“共享的”),并且只有当所有共享指针都消失时,该对象才会被销毁。此外,您可以观察弱指针,如果它们跟随的共享指针消失,它们将智能地得到通知。

Internally, shared_ptrhas a lot more going on: There is a reference count, which is updated atomically to allow the use in concurrent code. Also, there's plenty of allocation going on, one for an internal bookkeeping "reference control block", and another (often) for the actual member object.

在内部,shared_ptr还有很多事情要做:有一个引用计数,它会自动更新以允许在并发代码中使用。此外,还有大量分配正在进行,一个用于内部簿记“引用控制块”,另一个(通常)用于实际成员对象。

But there's another big difference: The shared pointers type is alwaystemplate <typename T> class shared_ptr;, and this is despite the fact that you can initialize it with custom deleters andwith custom allocators. The deleter and allocator are tracked using type erasure and virtual function dispatch, which adds to the internal weight of the class, but has the enormous advantage that different sorts of shared pointers of type Tare all compatible, no matter the deletion and allocation details. Thus they truly express the concept of "shared responsibility for T" without burdening the consumer with the details!

但是还有一个很大的区别:共享指针类型总是template <typename T> class shared_ptr;,尽管您可以使用自定义删除器自定义分配器对其进行初始化。删除器和分配器使用类型擦除和虚函数调度进行跟踪,这增加了类的内部权重,但具有巨大的优势,即不同类型的共享指针T都是兼容的,无论删除和分配细节如何。从而真正表达了“共担责任T”的理念,而不用细节给消费者带来负担!

Both shared_ptrand unique_ptrare designed to be passed by value (with the obvious movability requirement for the unique pointer). Neither should make you worried about the overhead, since their power is truly astounding, but if you have a choice, prefer unique_ptr, and only use shared_ptrif you really need shared responsibility.

二者shared_ptrunique_ptr设计成由值传递(与用于唯一的指针明显的可移动性要求)。也不应该让您担心开销,因为它们的功能确实令人震惊,但是如果您有选择,请更喜欢unique_ptr,并且仅shared_ptr在您确实需要分担责任时才使用。

回答by Alok Save

unique_ptr
is a smart pointer which owns an object exclusively.

unique_ptr
是一个专门拥有一个对象的智能指针。

shared_ptr
is a smart pointer for shared ownership. It is both copyableand movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

shared_ptr
是共享所有权的智能指针。它是copyablemovable。多个智能指针实例可以拥有相同的资源。一旦拥有该资源的最后一个智能指针超出范围,该资源将被释放。

回答by neodelphi

When wrapping a pointer in a unique_ptryou cannot have multiple copies of unique_ptr. The shared_ptrholds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptris copied, this counter is incremented. Each time a shared_ptris destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.

将指针包装在 a 中时,unique_ptr您不能有多个unique_ptr. 的shared_ptr保持参考计数器,它计数所存储的指针的副本的数目。每次shared_ptr复制 a 时,此计数器都会递增。每次 ashared_ptr被破坏时,该计数器都会递减。当此计数器达到 0 时,存储的对象将被销毁。