Copy-on-Write (COW) Idiom

What is the Copy-on-Write Idiom?

In the copy-on-write (COW) idiom, copying an object does not copy its data. The copy and the original share one instance of the data, which neither of them changes. Only when one of them is about to change the data does it make a private copy and change that. Objects that are copied often but rarely changed therefore pay for a copy only when one is actually needed.

A common way to implement COW in C++ is to hold the data through a std::shared_ptr<const T>. Copying the object copies the pointer. A function that changes the data first checks whether the data is shared, and if it is, replaces the pointer with a pointer to a new copy. A simpler form, used when every change replaces the whole value, never changes the data in place: a change makes a new value and points to it, and the old value lives on for as long as anyone else points to it.

Why Use the Copy-on-Write Idiom?

  • Copies are cheap. Copying an object costs a pointer copy, however large its data is. This matters when objects that may hold large data, e.g., a molecule or a basis set, are copied to change a few unrelated values.
  • Copies keep value semantics. Unlike sharing a mutable object by reference, a change made through one copy is never seen through another. Code can treat the object as a value.
  • Sharing is safe. Since shared data is never changed, a reader never sees it change under it, and a copy can never dangle the way a reference to another object’s data can.

The costs are a reference count per shared value, a check before every change, and, for data shared between threads, an atomic reference count. COW does not help if most copies are changed soon after they are made. It is also easy to break: a function that hands out a non-const reference to shared data lets a caller change it without the check. The rules C++11 set for std::string, many of whose functions return non-const references and iterators, ruled out COW implementations of it. The atomic reference counts of COW strings can also make them slower than plain copies in multithreaded code.

Example

PluginPlay’s CallGraph design uses COW for the values of module inputs. A module’s settings are copied whenever a call graph is resolved, but most values are never changed by the call graph.

C++

#include <memory>
#include <string>
#include <utility>

template<typename T>
class CowValue {
public:
    explicit CowValue(T value) :
      m_data_(std::make_shared<const T>(std::move(value))) {}

    /// Reading never copies
    const T& get() const { return *m_data_; }

    /// Writing replaces the value, so copies that share the old value keep it
    void set(T value) {
        m_data_ = std::make_shared<const T>(std::move(value));
    }

private:
    std::shared_ptr<const T> m_data_;
};

// Usage:
// CowValue<std::string> a("A very large basis set");
// auto b = a;            // no copy of the string, a and b share it
// b.set("Another one");  // b points to a new string, a is unchanged

CowValue uses the simpler form: set replaces the whole value. A class that changes part of its data in place would check m_data_.use_count() and copy the data first if it is shared.

Python

Python names refer to objects, and assignment never copies, so sharing comes for free. COW is then a matter of never changing a shared object in place, which immutable types such as tuple and frozenset enforce.

class CowValue:
    def __init__(self, value):
        self._data = value  # treated as immutable

    def get(self):
        return self._data

    def set(self, value):
        self._data = value  # rebinds this object only


a = CowValue(("A", "very", "large", "basis", "set"))
b = CowValue(a.get())  # shares the tuple, no copy
b.set(("Another", "one"))  # a is unchanged