C++ function automatic generation rules

A class constructor consists of:

  • default constructor (no-argument constructor)
  • copy constructor
  • move constructor

Related assignment operators:

  • copy assignment operator
  • move assignment operator

The above methods or operators are automatically generated by the compiler in some cases:

  1. If no constructor is defined, a default constructor is automatically generated.
    1) If there are other custom constructors, you need to manually add the default constructor;
    2) Or use =default to display and add the default implementation;
    3) Otherwise, an error will be reported when compiling.
  2. Define the copy constructor, the move constructor will not be automatically generated.
    1) The move structure can be compiled and passed, and the copy structure will be called for execution.
  3. Defining the move constructor does not automatically generate a copy constructor.
    1) At this point, the copy construct cannot compile.
  4. Copy construction and copy assignment, and move construction and move assignment are not mutually exclusive, defining one does not prevent the compiler from automatically generating the other.

A class, member type, deletes the assignment structure, and the assignment structure of this class is also deleted by default.

class Base {
    
    
public:
    Base() {
    
    
        cout << "base ctor()\n";
    }

    Base(const Base& b) {
    
    
        cout << "base copy ctor()\n";
    }

    Base(Base&& b) noexcept {
    
    
        cout << "base move ctor()\n";
    }

    Base& operator=(const Base& b) {
    
    
        cout << "base copy =\n";
        return *this;
    }

    Base& operator=(Base&& b) noexcept {
    
    
        cout << "base move =\n";
        return *this;
    }

    ~Base() {
    
    
        cout << "base de-ctor\n";
    }
};

class Derive: public Base {
    
    
public:
    Derive() {
    
    
        cout << "derive: default\n";
    }

    Derive(const Derive& d): Base{
    
    d} {
    
    
        cout << "derive: copy ctor\n";
    }

//    Derive& operator= (const Derive& d) {
    
    
//        cout << "derive: copy =\n";
//            return *this;
//    }

//    Derive(Derive&& d): Base{move(d)} {
    
    
//        cout << "derive: move ctor\n";
//    }
//    Derive& operator= (Derive&& d) {
    
    
//        cout << "derive: move =\n";
//        return *this;
//    }

    ~Derive() {
    
    
        cout << "derive: de-ctor\n";
    }
};

Guess you like

Origin blog.csdn.net/yinminsumeng/article/details/131142868