Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we explicitly write a copy constructor if the class member is a vector?

Tags:

c++

stl

struct myType {
    vector<char*> ls;
};

Here ls is holding pointers to char. If a user-defined copy constructor for myType is not provided, will myType's default copy constructor do a deep copy of ls?

like image 754
user966379 Avatar asked Jan 25 '12 09:01

user966379


People also ask

Why do we need explicit copy constructor?

An explicit copy constructor is one that is declared explicit by using the explicit keyword. For example: explicit X(const X& copy_from_me); It is used to prevent copying of objects at function calls or with the copy-initialization syntax.

What is the correct argument for copy constructor?

Copy constructor takes a reference to an object of the same class as an argument.

Which class definition is likely to need a copy constructor?

Explanation: The copy constructor can be defined as private. If we make it private then the objects of the class can't be copied. It can be used when a class used dynamic memory allocation.

Under which conditions a copy constructor is called?

A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object.


2 Answers

Here ls is holding pointer to char. If copy constructor is not provided, will default copy constructor do the deep copy?

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

However, the memory pointed to by the char* elements inside the vector will of course not, since C++ doesn’t know and doesn’t care what the pointers point to.

But the solution here isn’t to provide a custom copy constructor. It’s to use a data structure instead of raw pointers (char*) which does. And this happens to be std::string (or std::vector<char> depending on the intent).


1 Thus creating a transitive closure of the copy operation – this is how deep copying is generally implemented, but of course an implementor of the copy operation can always break out of it.

like image 65
Konrad Rudolph Avatar answered Oct 13 '22 20:10

Konrad Rudolph


will default copy constructor do the deep copy?

Of course not. The compiler cannot know who owns the pointed-to memory.

If deep copy is required, you have to implement the copy constructor and manually copy each char* into new memory for the vector in the copied-to object.

If you use the char* as zero-terminated strings, then you should really use std::string instead. If you do, the default constructor is enough.

like image 24
Johann Gerell Avatar answered Oct 13 '22 22:10

Johann Gerell