tags:

views:

268

answers:

3

In writing a copy constructor for a class that holds a pointer to dynamically allocated memory, I have a question.

How can I specify that I want the value of the pointer of the copied from object to be copied to the pointer of the copied to object. Obviously something like this doesn't work...

*foo = *bar.foo;

because, the bar object is being deleted (the purpose of copying the object in the first place), and this just has the copied to object's foo point to the same place.

What is the solution here? How can I take the value of the dynamically allocated memory, and copy it to a different address?

+1  A: 

I do not see the context, but the code you posted doesn't seem like copying the pointer, it is exactly what you ask for — copying whatever it points to. Provided that foo points to the allocated object.

Michael Krelin - hacker
+3  A: 

You allocate new object

class Foo
{
    Foo(const Foo& other)
    {
        // deep copy
        p = new int(*other.p); 

        // shallow copy (they both point to same object)
        p = other.p;
    }

    private:
        int* p;
};
Nikola Smiljanić
+1  A: 

Say you have a class like this and you want your constructor to do a deep copy

class foo
{
   bar * thebar;
   ...
}

So, the first step of the solution is create a copy of the object pointed to by thebar by using the copy constructor of bar:

foo(const foo & original)
{
    this.thebar = new bar(*(original.thebar));
}

But wait, what if bar holds another pointer to another object that will be automatically freed?

class bar
{
    baz * thebaz;
    ...
}

You need the same strategy to apply at all levels, i.e. if you want one of your constructors to support true deep copy, then all of your constructors for the types which that can point to need to support deep copy also.

Tim Lovell-Smith