There is such code:
#include <iostream>
#include <string>
int returnnumber() { return 2; }
std::string returntext() { return "siema"; }
int main() {
std::cout << (returntext() += "cze") << std::endl; // siemacze
//std::cout << (returnnumber() += 2) << std::endl; error: lvalue required as left operand of assignment
return 0;
}
Why is it possible to change return value of std::string, but not int?
because std::string
is a class type with a defined +=
operator as a member function.
and the standard allows you to call member functions on rvalues.
a silly consequence of that is that
struct S { int x; };
S foo() { return S(); }
int main()
{
foo() = S(); // OK, uses member assignment operator.
foo().x = 666; // !Nah, can't assign to rvalue of built-in type.
}
compilation results:
Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C++ C++0x_extensions "ComeauTest.c", line 7: error: expression must be a modifiable lvalue foo().x = 666; // !Nah, can't assign to rvalue of built-in type. ^ 1 error detected in the compilation of "ComeauTest.c".
however, compilers differ (or used to differ) about how strictly they applied this subtle rule, or if at all.
cheers & hth.,
The left hand side of an assignment operator for a built-in type must be a modifiable lvalue but the return value of a function is always an rvalue if the function doesn't return a reference type.
operator+=
is a member function of std::string
and you can call a member function on an rvalue of class type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With