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?
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.
unique_ptr
does not require a fully defined type—only the constructor/destructor do. This makes it usable for pimpl. –
Slaw unique_ptr
doesn't require a fully defined type. unique_ptr
's destructor does. So does the destructor of a scoped_ptr
. If you make one a member of a class, you can just give that class a destructor which is implemented in the .cpp file rather than the header. –
Taverner scoped_ptr
anymore." unique_ptr
can do everything a scoped_ptr
can do and more. A const unique_ptr
is a scoped_ptr
, but better. So really, there's no point in using scoped_ptr
unless your compiler doesn't support unique_ptr
. The fewer pointer templates you have, the better. –
Taverner scoped_ptr
is more useful than const unique_ptr
: you can't reset pointers in const unique_ptr
, but if the pointer is already at class scope, I might as well use regular unique_ptr
. –
Adventurous unique_ptr
accepting incomplete types and const unique_ptr
being a better scoped_ptr
to your answer. I was about to add it as an amendment to your answer until I saw the comments. I think these are quite important facts. Nice answer regardless. –
Mythify 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.
unique_ptr<T> const
. –
Diurnal swap
, so it can also escape the scope. (Actually I have no idea why scoped_ptr forbids move but allows swap; this seems an inconsistency in the design.) –
Exigent © 2022 - 2024 — McMap. All rights reserved.
boost::scoped_ptr
require a fully defined type likeunique_ptr
? – Joerg