Copy-On-Write

To support so-called Copy-On-Write constructions, a template class COW is available to manage resources of a given type T.

Copying a COW object is the same as cloning the resource. So, when you want to modify the resource, be careful on which COW object you acquire the resource. If that is a temporary COW object, the resource will be cloned in the temporary object upon write, but the modified resource will subsequently be deleted if the temporary COW object is destroyed.

Interface

The class definition is:

template <class T>
class COW;

The COW has the following interface:

  COW(T *resource)  
Create a Copy-On-Write object that will manage the given resource. Do not delete the given pointer or modify the resource through the supplied pointer!
  const T &operator() const  
Returns a const reference to the resource that is potentially shared.
  T &operator()  
Returns a reference to the resource that is guaranteed not to be shared.
  bool operator==(const COW &that) const  
Returns true if two COWs are managing the same resource.
  bool operator!=(const COW &that) const  
Returns true if two COWs are notmanaging the same resource.

Example

#include <cassert>
#include <cvmlcpp/base/COW>

int main()
{
	using namespace cvmlcpp;

	COW<int> a(new int(3));

	assert(a() == 3);
	COW<int> b = a;
	assert(a == b);
	b() = 7;
	assert(a() == 3 && b() == 7);
	assert(a != b);
	return 0;
}