Writing a deep copy - copying pointer value

后端 未结 3 885
野趣味
野趣味 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;
    };
    

提交回复
热议问题