Suppose a function that create a class and return:
Foo getFoo ()
{
return Foo ("bar");
}
And second method:
Foo getFoo ()
{
Foo foo ("bar");
return foo;
}
Now I call it with const Foo & myFoo = getFoo()
Is the first method more efficient? They looked same to me, since they both create a temp variable and returns it, am I wrong?
They’re basically the same, although copy elision in the first one would be called ‘return value optimization’ (RVO) while in the second it would be ‘named return value optimization’ (NRVO). At one point there were compilers that could do RVO but not NRVO.