Are assignment operators “required” to return?

2019-04-24 10:38发布

问题:

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.



标签: c++ standards