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.
It's up to the compiler whether or not (and how) to optimize this, or anything else. Except for certain exceptions (e.g. copy elision), optimizations are allowed if and only if they don't affect the observable behavior ("as-if rule" mentioned in the other answer).
Depends on the kind of rvalue. 10 is a prvalue, which are not even objects starting with C++17. References can't bind to prvalues directly, so it's materialized into an xvalue first, which is a temporary.
If you passed an xvalue, the reference would bind directly to it.
The above applies to C++17, I'm not sure how things worked before.