问题描述
可能的重复:
pimpl:shared_ptr 或 unique_ptr
智能指针(boost)解释
有人可以解释 shared_ptr 和 unique_ptr 之间的区别吗?
Could someone explain differences between shared_ptr and unique_ptr?
推荐答案
这两个类都是智能指针,这意味着它们会自动(在大多数情况下)解除分配它们指向的对象,当该对象不再可用时参考.两者的区别在于每种类型可以有多少个不同的指针指向一个资源.
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.
当使用unique_ptr
时,最多可以有一个unique_ptr
指向任何一个资源.当那个 unique_ptr
被销毁时,资源会自动回收.因为任何资源只能有一个 unique_ptr
,任何试图复制 unique_ptr
的尝试都会导致编译时错误.例如,此代码是非法的:
When using unique_ptr
, there can be at most one unique_ptr
pointing at any one resource. When that unique_ptr
is destroyed, the resource is automatically reclaimed. Because there can only be one unique_ptr
to any resource, any attempt to make a copy of a unique_ptr
will cause a compile-time error. For example, this code is illegal:
unique_ptr<T> myPtr(new T); // Okay
unique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr
但是,unique_ptr
可以使用新的移动语义移动:
However, unique_ptr
can be moved using the new move semantics:
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;
}
这个习语的意思是我将一个托管资源返回给你.如果你没有明确捕获返回值,那么资源将被清理.如果你这样做了,那么你现在拥有该资源的独占所有权."这样,您可以将 unique_ptr
视为 auto_ptr
的更安全、更好的替代品.
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_ptr
as a safer, better replacement for auto_ptr
.
shared_ptr
另一方面,允许多个指针指向给定的资源.当资源的最后一个 shared_ptr
被销毁时,该资源将被释放.例如,这段代码是完全合法的:
shared_ptr
, on the other hand, allows for multiple pointers to point at a given resource. When the very last shared_ptr
to a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:
shared_ptr<T> myPtr(new T); // Okay
shared_ptr<T> myOtherPtr = myPtr; // Sure! Now have two pointers to the resource.
在内部,shared_ptr
使用引用计数来跟踪有多少指针引用一个资源,所以你需要注意不要引入任何引用循环.
Internally, shared_ptr
uses reference counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.
简而言之:
- 当您想要一个指向某个对象的指针时,请使用
unique_ptr
,该对象将在该指针被销毁时回收. - 当您希望多个指针指向同一资源时,请使用
shared_ptr
.
- Use
unique_ptr
when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. - Use
shared_ptr
when you want multiple pointers to the same resource.
希望这有帮助!
这篇关于unique_ptr 和 shared_ptr 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!