Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not implement deep copy in default copy constructor?

Tags:

c++

All people keep remind us of the case when using default copy constructor and default assign operator, be careful since they're shadow copy. However, I am always confused why not make deep copy by default among default copy constructor and default assign operator in c++, so that no one need to write their own copy constructor implementation in order to prevent any accident?

like image 382
guo Avatar asked Jun 05 '16 09:06

guo


People also ask

Is default copy constructor a deep copy?

It doesn't do either. It does a memberwise copy. I.e. it copies all the members of the class using their copy constructors. If those members have copy constructors that do a deep copy then you'll get a deep copy, if they do a shallow copy then you'll get a shallow copy, or they could do something else entirely.

Is default copy constructor shallow copy?

The default version of the copy constructor (created by the compiler) makes what is known as a shallow copy. This simply means that the object is copied exactly as is -- each member data value is copied exactly over to the corresponding member data location in the new object.

What happens if you use the default copy constructor for vector?

The default copy constructor will copy all members – i.e. call their respective copy constructors. So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.


1 Answers

C++ implement copy by value, which means it basically does x = y;. In many cases this is enough.

However, in the case of pointers the compiler knows nothing about what is pointed to. It will copy the value of the pointer, but will not duplicate the underlying item because of this. For example, if you've got a class like this:

class Foo
{
  char *data;
};

Then what should the compiler do with data? It doesn't know if it points to a single char or an array of char. It doesn't know anything about how the memory was allocated or how it should be freed. It doesn't know if it should make a copy, or if all instances of Foo should point to the same instance.

Because of this the language takes a perfectly reasonable default stance, which is that only the value of the pointer will be copied. If you want anything more then you have to do it yourself as only you fully understand the use-case of the variable.

like image 57
Sean Avatar answered Oct 06 '22 00:10

Sean