对于持有通用成员的类,该如何完成?

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


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

关于c++ - 实现写时复制,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9171278/

10-10 11:46