Copy constructor assignment operator overload in php

  • 2020-05-19 04:21:18
  • OfStack

Object assignment and copy: assignment: overloaded with the "=" operator
User a(10),b;
b = a;
Copy: the copy constructor is called
User b;
User a(b);
or
User a = b; // equivalent to User a(b);
Unlike assignment, which is the assignment of an existing object (the object to which the implementation has defined the assigned object), replication is the creation of a new object from scratch and making it identical to an existing object.
Shallow replication and deep replication: if there is a pointer member in the object, the address of the pointer member will only be copied to the newly established object during the replication. Therefore, the pointer member in both objects points to the same memory area, and the problem of repeated release will occur when the pointer member is released. You need to manually define a copy constructor, in which new memory is allocated for pointer variables, so that pointer members of different objects point to different memory regions.
Use copy constructor three situations: 1, the need to create a new object, and the other a similar object to initialize the object of a class 2, function parameters, in the calling function need to establish a copies of argument, according to the argument to copy one parameter, system are realized by invoking the copy constructor function return value is a class of the object: at the end of the function call, you need to copy a temporary object in the function object, and calls to this function.

User getUser()
{  
User temp;  
return temp;
}
int main()
{  
User user = getUser();// call getUser();
}

At the end of the getUser() function call, the life cycle of the temp object established in getUser ends (it is about to be destroyed), so instead of taking temp back to main, when the return statement is executed, the copy constructor of User class is called, a new, object is copied by temp, and then it is assigned to user.

Related articles: