开发者

Writing a deep copy - copying pointer value

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?


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;
};


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.]


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜