I am a C++ newbie and I am struggling on the temporaries topic. I don't find anywhere a clear list of all cases in which the compiler will create a temporary. Actually, a few days ago I had in mind that when we pass an rvalue as const reference parameter, then the compiler will create a temporary and will put the rvalue into that temporary to hold it, passing the temporary as the parameter. Giving this example to my teacher,
void func(const int& _param){}
int main()
{
func(10);
// int __tmp__ = 10;
// func(__tmp__);
return 0
}
he said in this case the compiler won't create a temporary, but instead will directly optimize the code replacing 10 in all the occurrences inside the function body, so after that, I am more confused than ever.
10
would bind to one. i.e.void func(double&& d); ... func(10);
. If you want to say that the expression10
is a temporary I guess you can. godbolt.org/z/1jh4f44jo – Gewgaw__tmp__
is reserved for use by the compiler and supporting libraries and should not be used in any other code. If you use it in your own code you'll probably get away with it. But when you don't get away with it the results are utterly bizarre and nigh-inscrutable, so it's a situation best (and easily) avoided completely. – Fulminantint
object from the prvalue10
. Of course this doesn't mean that the executable produced by the compiler will reserve stack space for it, but they could e.g. take its address and use it the same way as any other object. – Drillingdouble
object from the prvalue10
. The reference is bound to that temporary object, not theint
prvalue10
from which the temporary is initialized. More generally what I want to say is that the word "temporary object" has a well-defined meaning in the language specification. – Drillingint
. – Gewgaw