Boost logo

Boost :

Subject: Re: [boost] [smart ptr] Any interest in copy-on-write pointer for C++11?
From: Mathias Gaunard (mathias.gaunard_at_[hidden])
Date: 2013-02-08 12:01:37

On 08/02/13 16:16, Ralph Tandetzky wrote:
> Hi,
> is there any interest in a copy-on-write pointer implementation? I wrote
> a cow_ptr<T> template class for C++11 which has the following use cases:
> 1. They are well suited as pimpl pointers for classes with value
> semantics. With most other smart pointers it is always necessary to
> reimplement the copy constructor, and the copy assignment operator,
> sometimes also the destructor. This is not necessary here and you'll
> get the right semantics and even the additional performance gain due to
> lazy copying. A futher advantage is that constness of cow pointer
> member functions propagates to the Impl object naturally making it
> easier to write const-correct code.

I don't see any reason to make this use lazy copying/COW.
COW is only useful if you're copying when you do not want to. The
solution is easy: do not copy if you don't want to; this is made easier
when you have the option to move instead.
COW could be used as an alternative implementation for compatibility
with code that isn't move-aware, but that's essentially the only use case.

Now the reason why this isn't more common is that there is no clean way
to copy an object polymorphically.

There are two approaches:
- You can use the static type of the object when inserted and assume it
is the same as the dynamic type. That's not ideal, and this requires
storing that information separately, adding a bit of space overhead.
This is the approach boost::any uses.
- You can make types that need polymorphic copy to have some sort of
virtual copy constructor, which follows the same principle as other
virtual functions. A member function of declaration T* clone() const is
often used, but this has obvious problems with flexibility, since it
couples allocation and construction. The best you can do is add two
functions, one that gives the size and alignment, the other that
constructs an object at a given address. With this approach, even if you
insert an object from a reference/pointer to base, the derived object
will correctly get copied, which is a very useful property when writing
code that uses polymorphism with value objects.

 From your description, I take it you're using the first approach.

Finally, and this will be my last complaint with this design, is that
what you're modeling isn't really a pointer, but rather a smart object.
It might therefore be worthwhile to change not only the name, but also
the interface so that construction takes references rather than pointers.

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