Because you can (but shouldn't!) Redefine operator =, so calling it on rvalue makes sense. Consider the following code:
#include<iostream> using namespace std; class foo; foo* gotAssigned = NULL; int assignedto = -1; class foo { public: foo(int v) : val(v) {} foo& operator=(int v) { assignedto=v; gotAssigned = this; val = v; return *this; } int val; }; foo theFoo(2); foo returnTheFooByValue() { return theFoo; } main() { returnTheFooByValue()=5; cout << "[" << assignedto << "] " << theFoo.val << " versus " << gotAssigned->val << endl; }
Now let's compile it in several ways:
$ g++ -O0 -o rveq rveq.cc && ./rveq [5] 2 versus 5 $ g++ -O1 -o rveq rveq.cc && ./rveq [5] 2 versus 2 $ g++ -O4 -o rveq rveq.cc && ./rveq [5] 2 versus -1218482176
I can not promise that you will see the same results.
As you can see, assignment occurs, but any attempt to use the assigned object leads to implementation-specific behavior.
By the way, this applies only to custom types. This code:
int v(){ return 2; } main(){ v()=4; }
not compiled.
source share