Writing a policy-based duplicating pointer
Let’s leave aside the standard smart pointers for a moment. Suppose we seek to write a smart pointer type whose semantics fit neither the sole ownership mold of std::unique_ptr<T>
nor the shared ownership mold of std::shared_ptr<T>
. For the sake of this example, suppose more specifically that we want single ownership semantics but, unlike std::unique_ptr<T>
, which is movable but non-copyable, we want duplication of the pointer to lead to duplication of the pointee. What can we do?
Well, this is C++, so we can of course write our own. Let’s call this new smart pointer type of ours dup_ptr<T>
(for “duplicating pointer”, or “pointer that duplicates the pointee”). Since we examined how one could implement sole ownership through our homemade unique_ptr<T>
earlier in this chapter, this section will mostly focus on the question of duplicating the pointee.
What do we mean...