class MyClass{};
MyClass ret_myclass() {return MyClass();}
int main()
{
ret_myclass(); // this will produce a temporary object before calling function to store the return value;
// and destruct it after calling
ret_myclass() = MyClass(); // correct
return 0;
}
If a function return a built-in type like int etc, is there also a temporary object?
1 2 3 4 5 6
int ret_int() {return 5;}
int main()
{
ret_int() = 5; // compile error
return 0;
}
In your case no function calls, no assigment and no temporary object creations are made.
Because compiler will optimize it all away.
In general case for ret_myclass function MyClass object will be created and them moved by calling move constructor (that is why you should define it following the rule of 5) or copied by calling copy constructor if move cc is not avaliable.
On line 5 it will be created and destroyed immideatly unless your classs it trivial enough for compiler to optimize it away.
on line 7 temporary creation and move assigment happens. Unless something is optimized away.
in your ret_init functions temporary is created (in sense that value of 5 is stored somewhere) and then returned. Unless optimizations happens. However most built-in types (and some of class type) rturned via registers so it is extremely fast (faster than function call in first place)
There is also inlining, optimizations and other things compiler does to generate efficient code.