Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: what's the design philosophy of allowing temporary object to call non-const member function?

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?

like image 650
Han XIAO Avatar asked Jan 27 '23 18:01

Han XIAO


1 Answers

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.

like image 146
n. 1.8e9-where's-my-share m. Avatar answered Jan 30 '23 13:01

n. 1.8e9-where's-my-share m.