If you are worried about the meaning and purpose of const &
vs. &
in the lists of function parameters, I'm afraid that you bark the wrong tree, since it has little to do with temporary objects.
void method( Object x );
This makes copy-construct a Object
of the actual argument. Any changes made to x
inside the function are lost, when the function ends, the function argument does not change.
But you do not want to pay the cost of copying.
void method( Object & x );
This does not copy the Object
construct from the actual argument, but x refers to the argument, that is, any changes made to x
inside the function are actually performed by the argument itself.
But you do not want the callers of the method to wonder what might happen to their arguments.
void method( const Object & x );
This does not copy-construct the Object
from the actual argument, and x
cannot be changed inside the function.
You do not pay for the constructor instance, and you explain to the caller that his argument will not be tampered with.
You cannot pass a temporary object as an argument to the second option (see unapersson answer), because there will be no changed object for the link, but since this function loudly declares that it will change the argument (since it declared a non-constant link), transfer the time argument is insensitive anyway.
source share