std::unique_ptr<T,D>
is specified to store not a T*
as you might expect, but an object of type std::unique_ptr<T,D>::pointer
. This is defined to be basically D::pointer
if such a type exists, and T*
otherwise. Thus, you can customize the underlying raw pointer type by customizing your deleter appropriately.
When is it a good idea to do this? What is it used for? The only discussion I've been able to find is this note, which alludes to "better support[ing] containers and smart pointers in shared memory contexts", but that doesn't exactly shed a lot of light.
Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another.
An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.
std::unique_ptr::reset Destroys the object currently managed by the unique_ptr (if any) and takes ownership of p. If p is a null pointer (such as a default-initialized pointer), the unique_ptr becomes empty, managing no object after the call.
unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to unique_ptr::reset.
The original motivation was to enable the use of boost::offset_ptr
as the representation under unique_ptr
, which would enable the use of unique_ptr
in process-shared memory. Structures in process shared-memory should not contain pointers or references, only offsets.
I'm pleased to learn that the same feature can be useful in the Windows API.
It is used when the deleter
does not operate on T*
values, obviously. That is why the deleter
can specify a different data type than T*
. A common use case is Win32 handles:
Using std::unique_ptr for Windows HANDLEs
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