Writing a deep copy - copying pointer value

后端 未结 3 883
野趣味
野趣味 2021-02-06 01:02

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

相关标签:
3条回答
  • 2021-02-06 01:36

    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;
    };
    
    0 讨论(0)
  • 2021-02-06 01:40

    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 讨论(0)
  • 2021-02-06 01:46

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

    0 讨论(0)
提交回复
热议问题