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

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

Difference between boost::scoped_ptr<T> and std::unique_ptr<T>

c++unique-ptrscoped-ptr

提问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_ptrcan have a destructor object with it, similarly to how shared_ptrcan. 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_ptrcan。与 不同shared_ptr,析构函数类型是unique_ptr's 类型的一部分(就像分配器是 STL 容器类型的一部分一样)。

A const unique_ptrcan effectively do most of what a scoped_ptrcan do; indeed, unlike scoped_ptr, a const unique_ptrcannot be rebound with a resetcall.

Aconst unique_ptr能有效地完成 a 能做的大部分工作scoped_ptr;确实,与 不同scoped_ptr, aconst unique_ptr不能通过reset调用反弹。

Also, unique_ptr<T>can work on a Twhich is an incomplete type. The default deleter type requires that Tbe complete when you do anything to the unique_ptrthat 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_ptrowns 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_ptris 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没有可复制也不可移动。当您想确保在超出范围时删除指针时,它是首选。