What happens (exactly) if you leave out the copy-constructor in a C++ class?
What happens (exactly) if you leave out the copy开发者_如何学编程-constructor in a C++ class?
Is the class just memcpy'd or copied member wise?
The class is copied member-wise.
This means the copy constructors of all members are called.
The default copy constructor is made mebmber wise.
The same member-wise approach is also used for creating an assignment operator; the assignment operator however is not created if the class has reference members (because it's impossible to rebind a reference after construction).
You get the default copy that copies the contents from one object into the other one. This has the important side effect that every member containing a pointer is now shared between the original object and the copy.
Notice that with a member-wise copy, if you have allocated any memory, your data structures will share that memory allocated - so it is important, if you want to create a deep (independent) copy of data to create a copy constructor for structures which allocate memory. If your structure is not allocating memory, it is less likely to really require a copy constructor.
However, if you implement the copy constructor, don't forget the Rule of Three: copy constructor, assignment operator, destructor. If one is implemented, all three must be implemented.
Regards,
Dennis M.
精彩评论