Assignment and replication of objects: assignment: Overloading by the "=" operator
User A (a), B;
b = A;
Replication: Calling a copy constructor
User b;
User A (b);
Or
User A = b;//is equivalent to User A (b);
Unlike assignment, the assignment is to assign a value to an already existing object (the object that defines the assignment has already been implemented), while replication creates a new object from scratch and makes it the same as an existing object.
Shallow copy and deep copy: If a pointer member is present in the object, only the address of the pointer member is copied to the newly created object, so the pointer member in the two object points to the same memory area, and the issue of duplicate release occurs when it is released. A copy constructor needs to be defined manually, and new memory is assigned to the pointer variable in the constructor, and the pointer member of the different object points to a different memory region.
Three things to use for copy constructors: 1, need to create a new object, and another similar object to initialize it 2, the function of the parameters of the class object, in the call function needs to establish a copy of the argument, according to the actual parameter copy of the parameter, the system is by calling the copy constructor implementation of the 3, The return value of a function is an object of the class: At the end of a function call, the object in the function needs to be copied to a temporary object and passed to the call to the function.
Copy Code code as follows:
User GetUser ()
{
User temp;
return temp;
}
int main ()
{
User user = GetUser ();//Call GetUser ();
}
At the end of the GetUser () function call, the object created in GetUser is at the end of the lifecycle (about to be destroyed), so instead of bringing the temp back to main, instead of calling the copy constructor of the user class when the return statement is executed, copy a new, object by temp, It is then assigned to user.