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
?
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.
Copy constructor takes a reference to an object of the same class as an argument.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With