C++ boost::scoped_ptr<T> 和 std::unique_ptr<T> 之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8199812/
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
Difference between boost::scoped_ptr<T> and std::unique_ptr<T>
提问by moshbear
Is the sole difference between boost::scoped_ptr<T>
and std::unique_ptr<T>
the fact that std::unique_ptr<T>
has move semantics whereas boost::scoped_ptr<T>
is just a get/reset smart pointer?
之间唯一的区别boost::scoped_ptr<T>
和std::unique_ptr<T>
一个事实,std::unique_ptr<T>
具有移动语义,而boost::scoped_ptr<T>
仅仅是一个GET /重置智能指针?
采纳答案by Nicol Bolas
No, but that is the most important difference.
不,但这是最重要的区别。
The other major difference is that unique_ptr
can have a destructor object with it, similarly to how shared_ptr
can. Unlike shared_ptr
, the destructor type is part of the unique_ptr
's type (the way allocators are part of STL container types).
另一个主要区别是unique_ptr
可以有一个析构函数对象,类似于 how shared_ptr
can。与 不同shared_ptr
,析构函数类型是unique_ptr
's 类型的一部分(就像分配器是 STL 容器类型的一部分一样)。
A const unique_ptr
can effectively do most of what a scoped_ptr
can do; indeed, unlike scoped_ptr
, a const unique_ptr
cannot be rebound with a reset
call.
Aconst unique_ptr
能有效地完成 a 能做的大部分工作scoped_ptr
;确实,与 不同scoped_ptr
, aconst unique_ptr
不能通过reset
调用反弹。
Also, unique_ptr<T>
can work on a T
which is an incomplete type. The default deleter type requires that T
be complete when you do anything to the unique_ptr
that potentially invokes the deleter. You therefore have some freedom to play games about where that happens, depending on the situation.
此外,unique_ptr<T>
可以在T
不完整类型的a上工作。T
当您对unique_ptr
可能调用删除器的进行任何操作时,默认删除器类型要求完成。因此,您可以根据情况自由地玩关于发生位置的游戏。
回答by Alok Save
unique_ptr
owns an object exclusively.It is non-copyablebut supports transfer-of-ownership. It was introduced as replacement for the now deprecated auto_ptr
.
unique_ptr
独家拥有一个对象。它是不可复制的,但支持所有权转让。它是作为现已弃用的auto_ptr
.
scoped_ptr
is neither copyable nor movable. It is the preferred choice when you want to make sure pointers are deleted when going out of scope.
scoped_ptr
是没有可复制也不可移动。当您想确保在超出范围时删除指针时,它是首选。