Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about the type of raw pointer inside unique_ptr

I read the book [The C++ Standard Library Second Edition] and found the section below:

namespace std {
template <typename T, typename D>
class unique_ptr<T[], D>
{
public:
typedef ... pointer; // may be D::pointer
typedef T element_type;
typedef D deleter_type;
...
};
}

The element type T might be void so that the unique pointer owns an object with an unspecified type, like void* does. Note also that a type pointer is defined, which is not necessarily defined as T*. If the deleter D has a pointer typedef, this type will be used instead. In such a case, the template parameter T has only the effect of a type tag, because there is no member as part of class unique_ptr<> that depends on T; everything depends on pointer. The advantage is that a unique_ptr can thus hold other smart pointers.

I still cant not understand the purpose of "everything depends on pointer" after i reading this section.Is there anyone could provide some samples kindly?Thanks.

like image 568
linus linus Avatar asked Nov 15 '25 10:11

linus linus


1 Answers

LWG issue 673 added pointer to the unique_ptr specification. It contains this bullet point for motivation:

  • Efforts have been made to better support containers and smart pointers in shared memory contexts. One of the key hurdles in such support is not assuming that a pointer type is actually a T*. This can easily be accomplished for unique_ptr by having the deleter define the pointer type: D::pointer. Furthermore this type can easily be defaulted to T* should the deleter D choose not to define a pointer type (example implementation here[broken link]). This change has no run time overhead. It has no interface overhead on authors of custom delter types. It simply allows (but not requires) authors of custom deleter types to define a smart pointer for the storage type of unique_ptr if they find such functionality useful. std::default_delete is an example of a deleter which defaults pointer to T* by simply ignoring this issue and not including a pointer typedef.

See boost::offset_ptr for an example smart pointer that can reference shared memory.

like image 105
Howard Hinnant Avatar answered Nov 16 '25 22:11

Howard Hinnant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!