Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is unique_ptr::deleter_type::pointer for?

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.

like image 562
Geoff Romer Avatar asked Feb 08 '14 00:02

Geoff Romer


People also ask

What is unique_ptr used for?

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.

Do I need to delete unique_ptr?

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.

What does unique_ptr Reset do?

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.

Does unique_ptr call Delete?

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.


2 Answers

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.

like image 96
Howard Hinnant Avatar answered Oct 12 '22 01:10

Howard Hinnant


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

like image 34
Remy Lebeau Avatar answered Oct 12 '22 01:10

Remy Lebeau