何时调用复制分配操作符?

时间:2021-05-05 05:32:17

When I read about copy constructor and copy assignment constructor, what I understood is that both gives away their properties one to another, and that both of them are declared implicitly by compiler (if not defined). So both must be exist whether doing something useful or not.

当我读到关于复制构造函数和复制赋值构造函数时,我理解的是,它们都将各自的属性传递给另一个,并且它们都是由编译器隐式声明的(如果没有定义的话)。所以无论做什么有用的事还是没用的事,两者都必须存在。

Then I tested this code:

然后我测试了这个代码:

#include <iostream>

using namespace std;

class Test {
public:
    Test () {
        cout << "Default constructor" << endl;
    }

    Test (const Test& empty) {
        cout << "Copy constructor" << endl;
    }

    Test& operator=(const Test& empty) {
        cout << "Copy assignment operator" << endl;
    }
private:

};

int main () {
    Test a;     // Test default constructor
    Test b (a); // Test copy constructor
    Test c = b; // Test copy assignment constructor
    system ("pause");
    return 0;
}

But it seems the copy assignment operator is not called at all. I tried with three conditions:

但似乎根本没有调用复制分配操作符。我尝试了三个条件:

  1. Everything included. It prints out:

    一切都包括在内。它打印出:

    // Default constructor
    // Copy constructor
    // Copy constructor    # Why not prints out "Copy assignment operator"?
    
  2. Whitout copy assignment operator just copy constructor. It prints out:

    删除复制分配操作符,只复制构造函数。它打印出:

    // Default constructor
    // Copy constructor
    // Copy constructor    # Why it's printed out even though I didn't define it?
    
  3. Whitout copy constructor just copy assignment operator. It prints out:

    删除复制构造函数,只需复制赋值操作符。它打印出:

    // Default constructor # Why "Copy assignment operator" is not printed out?
    
  4. Only constructor. It prints out:

    只有构造函数。它打印出:

    // Default constructor # Understandable
    

So, it's like the compiler doesn't even care if I define the copy assignment operator or not. None of the four examples above prints out "Copy assignment operator". So when did it get called, if it is really exists and has a meaning?

就好像编译器根本不在乎我是否定义了拷贝赋值运算符。上面的四个例子都没有打印出“复制分配操作符”。那么,如果它真的存在并且有意义,它是什么时候被调用的呢?

1 个解决方案

#1


13  

Test c = b is an initialization, not an assignment.

测试c = b是一个初始化,而不是一个赋值。

If you had done this:

如果你这样做了:

Test c;
c = b;

Then it would have called the copy assignment operator.

然后它会调用拷贝赋值操作符。

#1


13  

Test c = b is an initialization, not an assignment.

测试c = b是一个初始化,而不是一个赋值。

If you had done this:

如果你这样做了:

Test c;
c = b;

Then it would have called the copy assignment operator.

然后它会调用拷贝赋值操作符。