Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is += valid temporaries in standard library?

Tags:

c++

temporary

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?

like image 765
Clinton Avatar asked Mar 08 '12 01:03

Clinton


2 Answers

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).

like image 87
Dietmar Kühl Avatar answered Oct 11 '22 14:10

Dietmar Kühl


string& operator+= ( const string& str ); 

feel the difference

like image 22
Dmitriy Kachko Avatar answered Oct 11 '22 15:10

Dmitriy Kachko