复制赋值运算符什么时候调用? [英] When is the copy assignment operator called?

查看:161
本文介绍了复制赋值运算符什么时候调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读有关复制构造函数和复制赋值构造函数的信息时,我了解到两者都将它们的属性相互赋予,并且它们都是由编译器隐式声明的(如果未定义)。所以无论是否做有用的事情,两者都必须存在。

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. 包括的所有内容。它会打印出来:

  1. Everything included. It prints out:

// Default constructor
// Copy constructor
// Copy constructor    # Why not prints out "Copy assignment operator"?


  • Whitout复制赋值运算符只是复制构造函数。它会打印出来:

  • 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?
    


  • Whitout复制构造函数只是复制赋值运算符。它会打印出:

  • Whitout copy constructor just copy assignment operator. It prints out:

    // Default constructor # Why "Copy assignment operator" is not printed out?
    


  • 仅构造函数。它会打印出:

  • 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?

    推荐答案

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

    如果您已这样做:

    Test c;
    c = b;
    

    然后它将调用副本分配运算符。

    Then it would have called the copy assignment operator.

    这篇关于复制赋值运算符什么时候调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆