Question

Among other things, the chapter (12) on Dynamic Memory in C++ Primer (5th Edition) mentions a couple of constructors on shared_ptr and unique_ptr that I couldn't find online. I am writing this question to clarify the existence of these two constructors. If they do exist, specific questions about them have been asked below

  1. shared_ptr<T> p(p2, d): p is a copy of the shared_ptr p2, except that p uses the callable object d in place of delete

    I don't get the portion on the deleter here: p will point to the same underlying object as p2, and the reference count gets incremented by 1. While defining p2, one would have already specified a custom deleter, or used the default delete. What is the point of specifying a new deleter here?

  2. unique_ptr<T, D> u(d): Null unique_ptr that points to objects of type T that uses d (which must be an object of type D) in place of delete

    Now, this makes complete sense. However, I found a similar constructor for shared_ptr, but nothing for unique_ptr

Here are the resources I looked into:

shared_ptr:

  1. http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/
  2. http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

unique_ptr:

  1. http://www.cplusplus.com/reference/memory/unique_ptr/unique_ptr/
  2. http://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr

Just wanted to confirm whether they are legitimate or not?

Was it helpful?

Solution

In 20.7.2.2 The only constructors for shared_ptr I see that accept a deleter are ones that accept raw pointers or nullptr_t.

For unique_ptr, from 20.7.1.2 it looks like you could concoct a deleter type for which the underlying typedef would be another unique_ptr, but in order to retain the correct semantics you would have to take ownership of the object itself, so changing the deleter wouldn't necessarily be a problem (for example you might change it from immediate delete to return-to-pool on the fly).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top