|
Boost : |
Subject: [boost] [smart ptr] Any interest in copy-on-write pointer for C++11?
From: Ralph Tandetzky (ralph.tandetzky_at_[hidden])
Date: 2013-02-08 10:16:12
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.
// central_class_with_value_semantics.h
class CentralClassWithValueSemantics
{
public:
// ... public interface goes here ... //
private:
struct Impl; // forward declaration
cow_ptr<Impl> m;
};
// central_class_with_value_semantics.cpp
struct CentralClassWithValueSemantics::Impl
{
// ... definition of hidden members goes here ... //
}
This is called the pimpl idiom, or private implementation idiom, handle
body idiom, or compiler firewall idiom.
2. For classes with members whose copy-operations are expensive and/or
which take a lot of space in memory, these members can be wrapped in a
cow pointer. An example are matrix or image classes whose data might be
stored in a std::vector. The matrix header information may be changed
without deep copy. This boosts performance and optimizes memory usage,
but at the same time retains the value semantics one feels comfortable with.
class Matrix
{
public:
// ... public interface goes here ... //
private:
size_t nRows, nCols; // can be touched without deep copy.
cow_ptr<std::vector<float>> data; // copy-on-write
}
In such classes the default version of copy and move construction will
usually work just fine.
3. You can add cloning to a class hierarchy from the outside. With
cow_ptr<Base> a( new Derived1 );
cow_ptr<Base> b( new Derived2 );
cow_ptr<Base> c;
c = a; // performs a shallow copy.
c->doSomething(); // makes a deep copy of a as a Derived1
class.
// There is no slicing involved.
you copy Base objects polymorphically. The class Base can even be
abstract here. It is only required that Derived1 and Derived2 be
CopyConstructible.
4. You can create arrays with elements that retain polymorphic behaviour
and have genuine value sematics at the same time with
std::vector<cow_ptr<Base>>
polymorphic_array_with_value_semantics;
-- There are probably other use cases. I published the code on github ( https://github.com/ralphtandetzky/cow_ptr). Any suggestions for improvements would be greatly appreciated. Regards, Ralph Tandetzky.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk