Boost logo

Boost :

Subject: Re: [boost] [smart ptr] Any interest in copy-on-write pointer for C++11?
From: David Stone (david_at_[hidden])
Date: 2013-02-13 21:15:46

It seems to me that this class has some overloaded duties:

1) Allowing value semantics on polymorphic objects

2) Implementing copy-on-write

3) (not mentioned explicitly yet) allowing objects that would normally
be expensive to move to become cheap to move

It seems like a better solution would be to separate these into two
classes, on implemented in terms of the other:

First, something more like a proposed value_ptr. It would allow 1 and
3 only. I personally see many use cases for this. 1 is obvious, but 3
allows you to, for example, create a std::vector of value_ptr that
handles insertion into the middle with dramatically better overall
performance than std::vector and std::list in many use cases.
value_ptr could be easily implemented in terms of std::unique_ptr,
with the addition of a copy constructor and copy-assignment operator
to perform a "deep copy". The main questions for this class would be
whether it allows nullptr values and the inclusion of the release
member function (in line with goal 3, but out of line with goal 1) and
how the cloning is implemented.

Second, your cow_ptr (with hopefully a different name). This could
probably be implemented with no loss of efficiency as a wrapper around
a value_ptr, dramatically simplifying the implementation. I have no
interest in the overhead of copy-on-write, but was planning on writing
a value_ptr class. value_ptr seems to be an important enough building
block to justify inclusion on its own, and copy-on-write is a
fundamentally different problem than value-semantics. As such, the two
should not be coupled to each other.

For the cloning, have you considered a template function rather than
requiring a virtual clone member function? The template function
approach was used for the boost::ptr_container library. I disagree
with their design decision of providing a default implementation for
everything, though, as that seems like it could lead to errors. You
could, for instance, create a template function (like the
ptr_container library uses), such as new_clone, and use SFINAE on
!std::is_class<T> to provide a default implementation of a plain copy
(which is always safe on non-class types, as they cannot be the base
of anything), and require users to define their own overload for their
class. Have you considered this design decision? It seems that this
would work easier for non-class types, such as std::array.

Boost list run by bdawes at, gregod at, cpdaniel at, john at