This post will introduce two members in C++ class. The first is copy constructor that can perform a deep copy for member variables. Another one is assignment operator which is used to assign one to another by overloading =
operator.
Compiler provided
Usually, if there is no copy constructors and assignment operator in a class, the compiler will give default ones of member-wise copy version.
|
|
which means, for a class:
the default copy constructor and assignment operator provided by compiler like:
In many cases, this is sufficient. However, there are some circumstances where the member-wise copy version is not good enough. The commont reason of that is the object contains a raw pointer witch points to a block of memory. In this case, the member-wise copy is likely to lead to more than one pointers that points to the same block of memory which will be a heap curruption in objects destruction.
To avoid this curruption, copy constructor and assignment operator need to be implemented.
Copy constructor & Assignment operator
|
|
Many of the STL containers and algorithms require that an object should be copyable. Typically, this means that you need to have the copy constructor that takes a const reference.
Disallow Copy constructor and Assignment operator
In some cases, it is not a safe operation to copy or assign an object. So, its copy constructor or assignment operator should be disabled explicitly. The most commont way for this is to make private constructor or operator and provide no implementation. Generally, a macro can be used to simplify this procedure.
|
|
push_back() of STL vector container
push_back()
operator in vector container will perform a deep-copy of object. Actually, push_back()
will call insert()
in low level.
|
|
result is: