The study notes C ++ copy constructor

Copy constructor

Copy constructor definitions

The copy constructor is a special constructor, the object-oriented class which reference parameter . Role is an object that already exists to initialize a new object of the same type.

class class name {

public :

    Class name (parameter); // Constructor

    Class name (const & object name class name); // copy constructor, you not want to modify the reference object passed in

    //       ...

};

Class name :: class (const name & class object name) implement the copy constructor //

} {Function body

Implicit copy constructor

l If the programmer does not declare a class initialization copy constructor, the compiler generates an implicit own copy constructor.

L constructor function is performed by: a data value for each member of the initial value as a target, initialization to establish the corresponding data members of the object.

“=delete”

If you do not want to be the object l copy constructor

n C ++ 98 Method: The copy constructor declared as private, and does not provide function to achieve.

n C ++ 11 Method: with "= delete" indicating the compiler does not generate a default copy constructor.

Example l:

Defined class Point {// Point class

public:

    Point (int xx = 0, int yy = 0) {x = xx; y = yy;} // constructor, inline

    Point (const Point & p) = delete; // indicating the compiler does not generate a default copy constructor

private:

    int x, y; // private data

};

Copy the three cases constructor is called

When l defines an object to another object of this class as the initial value, the occurrence of copy configuration;

l If the object is a class parameter of the function, the function is called using arguments object initialization parameter, copying the configuration occurs; such combinations write class constructor occurs

If the function return value of l is the object of the class, the function returns the calling function execution is completed, the return statement in a temporary object initialization unknown object is passed to the calling function, the copy constructor occurs at this time.

n This situation can be avoided by moving the unnecessary copying configured

Guess you like

Origin www.cnblogs.com/working-in-heart/p/12113486.html