9

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?

Anonymous
  • 4,167
  • 11
  • 47
  • 52
  • 1
    Question makes no sense. Please try and reformulate it, possibly posting more code that illustrates what you are asking about. –  Dec 20 '09 at 20:41
  • Need more information: The type of foo would be good. Any other members. An explanation of why you are not using a smart pointer? – Martin York Dec 20 '09 at 20:56
  • This deals with array but may be useful: http://stackoverflow.com/questions/255612/c-dynamically-allocating-an-array-of-objects/255744#255744 – Martin York Dec 20 '09 at 21:07

3 Answers3

19

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ć
  • 26,745
  • 6
  • 48
  • 60
2

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
  • 138,757
  • 24
  • 193
  • 173
2

I assume your class looks like this.

class Bar {
   Foo* foo;
   ...
}

In order to do a deep copy, you need to create a copy of the object referenced by 'bar.foo'. In C++ you do this just by using the new operator to invoke class Foo's copy constructor:

Bar(const Bar & bar)
{
    this.foo = new Foo(*(bar.foo));
}

Note: this solution delegates the decision of whether the copy constructor new Foo(constFoo &) also does a 'deep copy' to the implementation of the Foo class... for simplicity we assume it does the 'right thing'!

[Note... the question as written is very confusing - it asks for the 'value of the pointer of the copied from object' that doesn't sound like a deep copy to me: that sounds like a shallow copy, i.e. this.

Bar(const Bar & bar)
{
    this.foo = bar.foo;
}

I assume this is just innocent confusion on the part of the asker, and a deep copy is what is wanted.]

Tim Lovell-Smith
  • 15,310
  • 14
  • 76
  • 93