I search the stack overflow and people say it's stupid to modify temporary object, so binding temporary object to non-const lvalue reference is not allowed, like you can't pass a temporary object to a function with non-const lvalue reference.
Then why is temporary objects allowed to call non-const member function which has the potential to modify the object and do "stupid" things? You may say, "ha, that's allowed because we want to provide the programmer with some flexibility to do "stupid" things that are in fact not that stupid", which is the reason I can hardly buy because if I buy this excuse, I think that "binding temporary to non-const lvalue reference" can be justified using the same reason.
Thanks! I hardly find any relevant question here. They just told me it's an exception, but why we allow that exception?
OK, I am putting some additional materials here. The following materials are quoted from David Vandevoorde, Nicolai M. Josuttis, Douglas Gregor-C++ Templates_ The Complete Guide-Addison-Wesley (2017), C.2.1 The Implied Argument For Member Functions.
“An old special-case permits an rvalue to be bound to an lvalue reference to non-const type when that reference is the traditional implicit *this parameter”
struct S{
void f1() {}//the old rule
void f2() && {}
void f3() & {}
};
int main()
{
S().f1();//Here, I THINK const this is bound to non-const, thus allowing calling non-const member functions.(the comment here is not quoted from the book.)
S().f2();
S().f3();//not okay
return 1;
}
Use -std=c++11
compilation option.
So, this means C++ designers have realized that the old rule of allowing temporary objects, which have implicit const this*
, to call non-const member function is not so good. So in C++11 they introduced &
and &&
suffixing function declaration.
But when it comes to the design philosophy of the old rule of allowing temporary objects calling non-const member function, I think it's not worth diving into this. C++ 11 has make an effort to "emend" this.(Or let programmer control this.)