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 temporarystd::istringstreamto read a non-basic type (basic types are read by members):(yes, this is a silly example).