std::deep_ptr aka deep copying smart pointer has not yet been introduced to the STL though several C++ experts have proposed an implementation in the past. See n3339.pdf for one such proposal and a list of possible implementations.

In this post I want to share my implementation of deep copying pointer I recently came up with. Its interface is virtually identical to std::unique_ptr with the exception of additional cloner template parameter (a policy class) that specifies how deep copies are to be made. By default the pointer is copied by doing return (p ? new T{ *p } : nullptr); that is by invoking the copy constructor of T.

My example program illustrates how to create a cloning policy for polymorphic types; in other words how to make deep copies when deep_ptr<Base> actually points to some struct Derived : Base and types in a given inheritance hierarchy implement virtual S* clone():

Finally, and just like the std::unique_ptr, my pointer type can be used with a custom deleter:

del will be called on a pointer managed by p when it goes out of scope or when p is assigned to.


Example program on my GitHub account: deep_ptr.cpp. The implementation: deep_ptr.hpp.


Leave a Reply