Duplicating Variable Contents: The Copy Constructor
Sooner or later, you may need to assign the contents of one
To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the rvalue (result of the evaluation of the right side of the operator) to the lvalue (same for the left side). Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).
This same form of "extended copying" is also necessary for PHP's
Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()). A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:
The first part of the function is plain-vanilla argument retrieval.
After the (left out) modifications, however, it gets interesting:
The container of
If you omit the call to the copy constructor in this example, both
The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor. | |||