Reputation: 299
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
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?
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
:
unique_ptr
:
Just wanted to confirm whether they are legitimate or not?
Upvotes: 2
Views: 180
Reputation: 96291
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).
Upvotes: 2