1

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.

Melebius
  • 6,183
  • 4
  • 39
  • 52
  • later on in your code, accessing `foo2` will be more expensive than `foo1` – Piotr Skotnicki Aug 25 '14 at 10:34
  • 1
    If you only use the variable(s) inside the calling function, and don't store them for later processing (though you can't really do it with references), then the two uses are pretty much equivalent. They are not the same though, as in one case you have a copy and in the other a constant reference. Also, having a reference is an extra step of indirection, but the compiler will probably optimize it away. But if you're really worried, you should of course measure it, and try to profile it, and possibly look at the generated assembly code. – Some programmer dude Aug 25 '14 at 10:35
  • I would not use a reference to temporary object http://stackoverflow.com/questions/11560339/returning-temporary-object-and-binding-to-const-reference –  Aug 25 '14 at 10:44
  • 2
    @PiotrS.: Probably not; both options should produce identical code, assuming an optimising compiler. The compiler knows which object the reference is bound to, so there's no need to dereference it at runtime. – Mike Seymour Aug 25 '14 at 12:10
  • `foo2` is a reference, not a pointer. References might not require any storage. – M.M Aug 28 '14 at 11:24

0 Answers0