Pergunta

I try to implement copy on write using a pointer on integer. But I don't understand how to write the code. The idea is very clear in my head: when I use the default constructor, I create a new instance of the object (number of instances=1) and when I use the copy constructor, I increment the number of instances and make a shallow copy of the object.

    class Myclass
{
public:
    Myclass(const char * foo, int foo2) : foo(foo), foo2(foo2) 
    {
        (*ref)=1;
    }
    Myclass(const Myclass& rhs) :foo(rhs.foo),foo2(rhs.foo2) 
    {
        (*ref)++;
    }
    const char * foo;
    int foo2;
    int *ref;
};

I begin with C++ and the notion of pointer is completely news for me so I tried this. But I really don't understand why "ref" is still equal to 1 even if I create a copy of the object witht he copy constructor.

Foi útil?

Solução

Your default constructor needs to create a new reference count:

ref(new int(1))

And your copy constructor needs to make the new object end up with a pointer to the original object's reference count and to increment it (which you already do):

ref(rhs.ref)

Outras dicas

I'm having trouble understanding what you want but I'll try...

I create Myclass foo ("foo",10) and then Myclass foo2(foo). I want all ref to be equal to 2. Here only the ref of foo2 is equal to 2. The ref of foo is equal to 1. I think I need a pointer, no?

This can be accomplished with a static variable:

class Myclass
{
public:
    Myclass(const char * foo, int foo2) : foo(foo), foo2(foo2) 
    {
        ref += 1;
        if (1 == ref) {}    // First ref, do something?
    }
    Myclass(const Myclass& rhs) :foo(rhs.foo),foo2(rhs.foo2) 
    {
        ref += 1;
    }
    ~Myclass()           // Decrement on delete
    {
        ref -= 1;
        if (0 == ref) {} // Last reference. Do something?
    }
    const char * foo;
    int foo2;
    static int ref;
};
int Myclass::ref = 0;   // Initialize to 0

Then....

Myclass foo("foo",10);             // ref becomes 1
Myclass foo2(foo);                 // ref becomes 2
Myclass *foo3 = new Myclass(foo);  // ref becomes 3
delete foo3;                       // ref becomes 2
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top