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?
You cannot bind a temporary to a non-const reference, but the rationale here is not to avoid accidental modification of a temporary. The rationale is that you don't want to silently miss modifying something you wanted to modify.
Imagine it's allowed, then:
void foo(double& x);
int y;
foo(y); //user wants to modify y, but instead a temporary is modified
In and of itself, modifying a temporary object is perfectly OK and often useful. There's no reason to disallow it.
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