Difference copy constructor and assignment operator overloading

Look at an example:

#include<iostream>
using namespace std;
class Demo
{
public:
    //构造函数
    Demo(int num)
    {
        m_num = num;
        printf("constructor\n");
    }
    //拷贝构造函数
    Demo(const Demo & demo)
    {
        m_num = demo.m_num;
        printf("copy constructor\n");
    }

	//赋值运算符重载
    Demo& operator=(const Demo& demo)
    {
        m_num = demo.m_num;
        printf("operator=\n");
        return *this;
    }

    //析构函数
    ~Demo()
    {
        cout<<"destructor\n";
    }
private:
    int m_num;
};
int main()
{
    Demo A(100); // 产生一个实例,调用一次构造函数
    Demo B=A;    // 调用拷贝构造函数,产生一个实例

    Demo C(20);  // 产生一个实例,调用一次构造函数
    C = A;	     // 调用赋值运算符重载
    return 0;
}

Run Results: three times configured destructor

  

  By default (the user is not defined, but deleted also not shown), the compiler will automatically implicitly generate a copy constructor and assignment operator, but the user can delete the new standard to specify not generated copy constructor and assignment operator, such objects can not be passed by value, assignment operation can not be performed

Call opportunity:
 1) call the copy constructor: When you create a new object (including temporary objects and create objects pass parameters generated)

 2) Call assignment operator: the object has been generated

Published 343 original articles · won praise 57 · Views 200,000 +

Guess you like

Origin blog.csdn.net/jadeshu/article/details/103572297