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.
The "as-if" rule applies here. See https://en.cppreference.com/w/cpp/language/as_if.
Your job is to specify your intention by writing some C++ source code. The compiler's job is to turn that into machine code that matches the intention.
There's nothing in the C++ standard to tell you how many temporaries are created in your program. A good compiler will optimise your program to
If the creation of the temporary has an observable side-effect then the compiler's options are a little more restricted. But in NRVO and RVO circumstances it is allowed to ignore that. In later C++ standards it is required to.