简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM