Moule Lin
← All notes

Shallow and Deep Copy in C++

Shallow copy and deep copy
Shallow-copying a pointer causes heap data to be freed twice
Problem: While running algorithm experiments recently, I ran into a problem with assigning class pointers. A simple assignment between pointers just makes both point to the same address, but I needed to push_back the class pointer after each run of the algorithm into a vector to store the result of every iteration. If the same pointer were stored every time, all the class pointers in the vector would point to the same address. This made me wonder whether class pointers could be assigned so that the two have the same contents but point to different addresses, i.e. they are two distinct pointers.

Definitions

Shallow copy: as I understand it, data members are assigned from one object to another. For simple data types a shallow copy is perfectly adequate, but when there are pointers, a shallow copy between two objects makes their pointers point to the same address, and an error occurs when the destructors run (the same pointer is freed twice).

Deep copy: builds on the shallow copy but handles the pointer copying so that the pointers inside the two objects point to different regions; the two objects have the same contents but are stored in different areas of memory.
‘’’
class rect
{
public:

rect();
rect(const rect *r);
~rect();

private:
int width, height;
int *p;
};
rect::rect(const rect *r)
{
width = r->width;
height = r->height;
p = new int;
*p = *(r->p);
}

rect::rect()
{
p = new int(100);
}

rect::~rect()
{
if (p != NULL)
delete p;
}
int _tmain(int argc, _TCHAR* argv[])
{
rect *rect1;
rect *rect2;
rect1 = new rect;
rect2 = new rect(rect1);

return 0;

}
‘’’
Both the class pointers and the member pointer p now point to different addresses