@therockon7throw
There's no penalty; it can actually be more efficient to do that (even with an older C++98/03 compiler) because temporary objects are nearly always optimised out when you initialise an object from a function return.
For example, using a class which has no move semantics (i.e. legal C++98/03 code)
1 2 3 4 5 6 7 8 9 10 11 12 13
|
struct foo
{
foo() { std::cout << "Ctor" << std::endl; }
foo(const foo&) { std::cout << "CCtor" << std::endl; }
~foo() { std::cout << "Dtor" << std::endl; }
foo operator* (const foo&)
{
foo bar;
std::cout << "multiplication" << std::endl;
return bar;
}
};
|
Using method 1 as per the OP:
1 2 3 4 5 6 7 8 9
|
int main()
{
foo bar1;
{
foo bar2;
foo bar3;
bar1 = bar2 * bar3;
}
}
|
Output: (no function initialisation)
1 2 3 4 5 6 7 8 9 10 11
|
Ctor
Ctor
Ctor
Ctor
multiplication
CCtor
Dtor
Dtor
Dtor
Dtor
Dtor
|
Note that there are 5 objects created in total, including temporaries.
However, using a function call, one of those objects is optimised out automatically by the MS Visual C++ compiler:
1 2 3 4 5 6 7 8 9 10 11
|
foo create_foo()
{
foo bar2;
foo bar3;
return bar2 * bar3;
}
int main()
{
foo bar1 = create_foo();
}
|
Output: (Function initialisation)
1 2 3 4 5 6 7 8 9
|
Ctor
Ctor
Ctor
multiplication
CCtor
Dtor
Dtor
Dtor
Dtor
|
So, far from being a penalty, there's actually a benefit. (Which of course is compiler-dependent), however even on compilers which don't make this optimisation it should never be less efficient to do it this way
However, as I alluded to in my original post, optimisations alone aren't usually a good reason for doing something, but readability certainly is; the efficiency gained is more of a bonus.