Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a deep copy - copying pointer value

Tags:

c++

pointers

copy

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?

like image 318
Anonymous Avatar asked Dec 20 '09 20:12

Anonymous


People also ask

How do I copy value from one pointer to another?

The idea of "copying a pointer", when taken literally, is nothing more than a simple assignment. int x = 5; int* p1 = &x; int* p2 = p1; // there, we copied the pointer. In this case, both p1 and p2 point to the same data - the int variable x .

Can pointer be copied?

Copying a pointer does not copy the corresponding object, leading to surprises if two pointers inadvertently points to the same object. Destroying a pointer does not destroy its object, leading to memory leaks.

Can we use pointer in copy constructor?

Technically, you could write a constructor that takes a pointer (although it's technically not a copy constructor in that case, based on the wording of the spec). However, this prevents you from using non-addressable results.


1 Answers

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;
};
like image 186
Nikola Smiljanić Avatar answered Oct 03 '22 09:10

Nikola Smiljanić