实现写时复制

Implementing copy on write

本文关键字:复制 实现      更新时间:2023-10-16

对于一个拥有泛型成员的类,如何做到这一点,比如:

template<typename T> class SP
{
private:
    T* data;
    reference* ref;
    public:
        //Some methods here to access data
};

我发现了两种不同的写时复制(COW)方法:

COW Poiner

COWPtr<Object> cow(&obj);
const COWPtr<Object> &cow_ref = cow;
std::cout << cow_ref->name; // operator->() doesn't copy the object because its const overload is used
cow->name = "my object"; // here non const operator->() copies the object
(*cow).name // operator*() also copies the underlying object

来自Adobe stlab 的WRITE方法

COW<Object> cow(&obj);
std::cout << cow->name; // the object is not copied
cow.write().name = "my object"; // the object is copied here