I use functions that return an object, like Bar()
in the following example:
class Foo
{
public:
Foo(int _x, int _y) : x(_x), y(_y) {}
private:
int x, y;
}
Foo Bar()
{
return Foo(1, 2);
}
Not involving those with need for extra tools or lines of code (like returning a pointer or using std::auto_ptr
), I know two ways to store the returned object in a local variable when I want to read it (call const
methods only):
const Foo foo1 = Bar();
const Foo &foo2 = Bar();
Both of them are correct in C++, the first option should have no copy overhead.
Are there any differences between these two options in terms of performance? Should one of them be preferred?
EDIT
OK, I’ll add a reason why I care about this. Assume the implementation of Bar gets changed:
Foo globalFoo(1, 2); // This object could also be a class member.
Foo &Bar()
{
return globalFoo;
}
My original piece of code defining foo1
and foo2
should still work but foo2
gets bound to globalFoo
, so it requires less memory1, right? Is therefore using references better since it could profit from such changes of interface?
1 Assuming the usual case that an object takes more memory than a pointer.