Difference between boost::scoped_ptr and std::u

2020-02-17 05:48发布

问题:

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?

回答1:

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).

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.

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.



回答2:

unique_ptr owns an object exclusively.It is non-copyable but supports transfer-of-ownership. It was introduced as replacement for the now deprecated 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.