Consider this code:
struct foo {
int a;
};
foo q() {
foo f;
f.a = 4;
return f;
}
int main() {
foo i;
i.a = 5;
q() = i;
}
No compiler complains about it, even Clang. Why is the statement q() = ... correct?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, the return value of a function is an l-value if and only if it is a reference (C++03). (5.2.2 [expr.call] / 10)
If the type returned were a basic type then this would be a compile error. (5.17 [expr.ass] / 1)
The reason that this works is that you are allowed to call member functions (even non-
constmember functions) on r-values of class type and the assignment offoois an implementation defined member function:foo& foo::operator=(const foo&). The restrictions for operators in clause 5 only apply to built-in operators, (5 [expr] / 3), if overload resolution selects an overloaded function call for an operator then the restrictions for that function call apply instead.This is why it is sometimes recommended to return objects of class type as
constobjects (e.g.const foo q();), however this can have a negative impact in C++0x where it can inhibit move semantics from working as they should.