在写上实现副本

时间:2012-02-07 05:08:16

标签: c++ copy

如何为拥有通用成员的类完成此操作,例如:

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

1 个答案:

答案 0 :(得分:1)

我发现了两种不同的写入时复制方法(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

WRITE method from Adobe stlab

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