问题
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
?
回答1:
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.
回答2:
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.
回答3:
No, it will not.
C++ will recursively call the copy ctor of all subobjects. So it will call the copy ctor of the vector, which will in turn call the copy ctor of the char*
which will copy the char*
by value. C++ will never automatically allocate memory and copy the data. It can't even possibly do that, since it does not know what the data is you are pointing at, and how much it should copy.
When you use strings, you should prefer using std::string
, as this will do all the copying for you. If it is some binary data buffer that needs special handling, then you need to do that yourself in your copy ctor (and when you are done, think a moment about if it was really sensible to think about requiring C++ to do that for you).
When you write your own copy ctor, you always should mind the Rule of Three
来源:https://stackoverflow.com/questions/9000636/should-we-explicitly-write-a-copy-constructor-if-the-class-member-is-a-vector