简体   繁体   English

重载operator =时返回参考值和值有什么区别?

[英]What's the difference between returning a reference and value when overloading operator=?

Look here: 看这里:

class IntClass
{
public:
IntClass operator=(const IntClass& rhs);
IntClass();
~IntClass();
int value;

};

Implementation: 执行:

IntClass::IntClass()
{
}


IntClass::~IntClass()
{
}

IntClass IntClass::operator=(const IntClass& rhs)
{
    this->value = rhs.value;
    return *this;
}

As you can see I am not returning a reference to the class. 如您所见,我没有返回对该类的引用。 From the examples of overloading the = operator I see that people return a reference. 从重载=运算符的示例中,我看到人们返回了一个引用。 Why is this? 为什么是这样?

This still functions as intended: 这仍然按预期运行:

IntClass a, b, c, d;

a.value = 20;

b = c = d = a;

printf("%d", b.value);
printf("%d", c.value);
printf("%d", d.value);

Output: 202020 产出:202020

ps I know the public access to value is bad. 附言:我知道公众获取价值是不好的。

First, having your assignment operator return by value means that you are making an extra copy. 首先,让赋值运算符按值返回意味着您要制作一个额外的副本。 The copy can be expensive, and compilers usually cannot elide it. 该副本可能很昂贵,并且编译器通常无法淘汰它。 If we assume that copy assignment and copy construction have roughly the same cost, then returning by value basically doubles the cost of the assignment. 如果我们假设副本分配和副本构造的成本大致相同,则按值返回基本上会使分配成本加倍。

Second, if your assignment operator return a reference, the result of the assignment expression is an lvalue, which mimics the built-in assignment operator. 其次,如果您的赋值运算符返回一个引用,则赋值表达式的结果是一个左值,它类似于内置的赋值运算符。 If your assignment operator return by value, the result of the expression is an rvalue. 如果您的赋值运算符按值返回,则表达式的结果为右值。 This can have interesting consequences: 这可能会产生有趣的结果:

void f(IntClass &lv); 
void g(IntClass &&rv);
void g(const IntClass &clv);

IntClass x, y; 
y.value = 10;
f(x = y);  // compiles only if operator= returns IntClass & 
           // as non-const lvalue references cannot bind to a temporary
g(x = y);  // calls g(IntClass &&) if operator= returns IntClass
           // calls g(const IntClass &) if operator= returns IntClass &

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

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