When is the copy assignment operator called?

守給你的承諾、 提交于 2019-11-28 00:26:20

问题


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:


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

If you had done this:

Test c;
c = b;

Then it would have called the copy assignment operator.



来源:https://stackoverflow.com/questions/29154814/when-is-the-copy-assignment-operator-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!