Are assignment operators “required” to return?

三世轮回 提交于 2019-12-22 04:33:12

问题


According to the C++ standard, can I be sure that assignment operators for built-in variables return (the original value)?

Or is this implementation dependent (yet simply have most popular compilers implemented this)?


回答1:


Yes, it is guaranteed:

5.17 Assignment and compound assignment operators

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.

This applies to built-in types. With user-defined types it can return anything.




回答2:


It depends on what you mean by "the original value".

For example:

#include <iostream>
int main() {
    int i;
    std::cout << (i = 1.9) << "\n";
}

prints 1. The assignment expression yields the new value of the LHS (namely 1), not the "original value" of the RHS (1.9).

I'm not sure whether that's what you meant to ask about.




回答3:


According to the C++ standard, can I be sure that assignment operators for build in variables return (the original value)?

Edit I get it now, I think. Yes: you can be sure that the built-in types return the original value by reference after operator=, *=, /=, -=, +=, ^=, ~=, &= and |=.

"For build in variables" is a bit cryptic to me. However,

X makeX()
{
    return X();
} // must have accessible copy constructor

// ...
X x;
x = makeX(); // ... _and_ assignment operator

Or is this implementation dependent

It should not be (edit see standard reference by UncleBens)




回答4:


Yes. It is guaranteed that all assignments and augmented assignments on predefined types work that way.

Note however that user defined types assignments or augmented assignments can instead for example return void. This is not good practice and shouldn't be done (it raises the surprise effect on users - not a good thing), but it's technically possible so if you are writing for example a template library you should not make that assumption unless it's really important for you.




回答5:


Yes. Operator semantics will simply not work otherwise.



来源:https://stackoverflow.com/questions/8118600/are-assignment-operators-required-to-return

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