Why does unique_ptr have a deleter as a type parameter, but shared_ptr does not?

The std::unique_ptr has two parameters: a bridgehead type and a deleter type. This second parameter has a default value, so you usually just write something like std::unique_ptr<int> .

The std::shared_ptr has only one parameter: the receiver type. But you can also use a custom deleter with this, even if the deleter type is not in the class template. A typical implementation uses type erasure methods to do this.

Is there a reason why the same idea was not used for std::unique_ptr ?

+55
c ++ smart-pointers type-erasure
Jul 26 '11 at 11:51
source share
2 answers

Part of the reason is that shared_ptr needs an explicit control unit in any case to count the number of links and glue the deleter inside, this is not such a big deal from above. unique_ptr however does not require additional overhead, and adding it will be unpopular - it should be a class with zero load. unique_ptr assumed to be static.

You can always add your own type erasure from above if you want this behavior - for example, you can have unique_ptr<T, std::function<void(T*)>> , which I did in the past.

+35
Jul 26 '11 at 11:56 on
source share

Another reason, in addition to the one specified by DeadMG, would be that you could write

 std::unique_ptr<int[]> a(new int[100]); 

and ~unique_ptr invoke the correct delete version (via default_delete<_Tp[]> ) due to the specialization for both T and T[] .

+2
Jul 26 '11 at 13:21
source share



All Articles