Is that an accurate description of it? Does it make sense?
Are you guaranteed that the object it points to won't be deleted until the unique_ptr goes out of scope [even if you're not using the unique_ptr]?
std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
Smart pointer is a variation of RAII. RAII means resource acquisition is initialization. Smart pointer acquires a resource (memory) before usage and then throws it away automatically in a destructor.
unique_ptr is defined in the <memory> header in the C++ Standard Library. It is exactly as efficient as a raw pointer and can be used in C++ Standard Library containers.
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.
Yes, std::unique_ptr
follows the RAII design principle.
No, std::unique_ptr
does not prevent other code from doing something stupid, like calling delete
on a pointer that belongs to the unique_ptr
. The unique_ptr
itself will call a deleter1 on the object it owns when either:
or
unique_ptr
is reassigned (via operator=
or reset
) to point to a different objectOne can also revoke unique_ptr
's ownership of an object by moving to a different smart pointer, or using the release
member function. This breaks the association between the object and the unique_ptr
and unique_ptr
will no longer clean up the object.
1 The default deleter will use either delete
or delete []
, depending on whether the target has array type. But unique_ptr
is a template and its deleter can be customized, for example the cleanup operation for a FILE*
can be chosen to be a call to fclose
.
This capability can be used to schedule an arbitrary cleanup action to take place when the unique_ptr
goes out of scope. RAII is used for keeping locks, closing files, and so forth -- clearly there would be major problems if the cleanup action were performed early just because the compiler didn't see any future usage of the smart pointer. Luckily the C++ object lifetime rules are completely deterministic (even the order of destruction for multiple automatic variables in the same scope is well defined), and you can count on the smart pointer cleaning up its owned object exactly when the smart pointer is itself destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With