简体   繁体   English

何时调用复制赋值运算符?

[英]When is the copy assignment operator called?

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?那么它是什么时候被调用的,如果它真的存在并且有意义呢?

Test c = b is an initialization , not an assignment. Test c = b初始化,而不是赋值。

If you had done this:如果你这样做了:

Test c;
c = b;

Then it would have called the copy assignment operator.然后它会调用复制赋值运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM