Jump to content
  • Advertisement
Sign in to follow this  
luasitdown

what are Shallow copy and Deep copy?

This topic is 4848 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
Hi,

let's say you have an object with a dynamic array in it like so:


class A
{
private:
int* array;
};



and you want to copy the object.
Then you could copy the pointer (eg. share the pointer with the new copy)
or you could copy the complete array. The first is shallow and the second is deep copy.

In the fist one if you change something in the array of the copy it will also change in the orignal array. In the second one it will not, but the second one uses more memory.

Hope this helps.

Share this post


Link to post
Share on other sites
A deep copy also copies the data the member pointer variables point to. Shallow copying can be a source of memory leaks and double deletions if you aren't careful. Here are C++ examples.

Shallow copy
    struct Bar { ... };
struct Foo
{
Foo( Bar * b ) : bar(b) {}
// The default copy constructor and assignment operator perform shallow copies.
Bar * bar;
};

Foo f1( new Bar );
Foo f2( new Bar );
f1 = f2; // Oops, memory leak
Bar * b = new Bar;
Foo f3( &b1 );
Foo f4( f1 ); // f1.bar and f2.bar point to the same data
delete f3.bar;
delete f4.bar; // Oops, b was deleted twice
Deep copy
    struct Bar { ... };
struct Foo
{
Foo() : bar( 0 ) {}
Foo( Bar * b )
{
bar = new Bar( *b ); // Make a copy of what b points to
}
~Foo()
{
delete bar;
}
Foo( Foo const & src ) // Copy constructor
{
bar = new Bar( *src.bar ); // Make a copy of what src.bar points to
}
Foo & operator =( Foo const & rhs ) // Assignment operator
{
if ( this != &rhs )
{
delete bar; // Destroy the previous copy of what bar points to
bar = new Bar( *rhs.bar ); // Make a copy of what rhs.bar points to
}
}

Bar * bar;
};

Foo f1( new Bar );
Foo f2( new Bar );
f1 = f2; // No memory leak since f1.bar was deleted first
Bar * b = new Bar;
Foo f3( &b1 );
Foo f4( f1 ); // f1.bar and f2.bar point to different data
// delete f3.bar; // Not necessary
// delete f4.bar; // Not necessary
So, its a lot of code, but it is frequently necessary.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!