When I attempt to compile the following on ideone:
class X
{
public:
friend X& operator+=(X& x, const X& y);
};
X& operator+=(X& x, const X& y) { return x; }
int main()
{
X() += X();
}
As expected, this throws a compile error, because you can't pass a temporary to a non const reference.
However, the following compiles successfully on ideone:
std::string() += std::string();
Shouldn't this error like my example above?
Edit:
If std::string() defines +=
as a member operation, why does it do this when such usage allows the left hand side to be a temporary? Why not define it as I have above and avoid the reference to temporary issues?
The C++ rule is that you can't bind a temporary to a non-const reference. However, you can call non-const member functions on temporaries: if you define the operator +=()
as a member, you can call it on your object. This is one of the tricks how to get a reference out of temporary, e.g. when using a temporary std::istringstream
to read a non-basic type (basic types are read by members):
std::string word;
if (std::istringstream("hello world") >> std::ws >> word) { ... }
(yes, this is a silly example).
string& operator+= ( const string& str );
feel the difference
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