C++ – Return New Object Instance by Reference in C++

c++objectreferencereturnvariable-assignment

So I was writing some code, and I had something like this:

class Box
{
    private:
    float x, y, w, h;

    public:
    //...
    Rectangle & GetRect( void ) const
    {
        return Rectangle( x, y, w, h );
    }
};

Then later in some code:

Rectangle rect = theBox.GetRect();

Which worked in my debug build, but in release there were "issues" returning that Rectangle by reference — I basically got an uninitialized rectangle. The Rectangle class has an = operator and a copy constructor. Without getting into why this broke, I'm actually more interested in the correct way to return a (new) object by reference for the purpose of assigning copying to a variable. Am I just being silly? Should it not be done? I know I can return a pointer and then dereference on assignment, but I'd rather not. Some part of me feels like returning by value would result in redundant copying of the object — does the compiler figure that out and optimize it?

It seems like a trivial question. I feel almost embarrassed I don't know this after many years of C++ coding so hopefully someone can clear this up for me. 🙂

Best Answer

You can't return a reference to a temporary object on the stack. You have three options:

  1. Return it by value
  2. Return by reference via a pointer to something that you created on the heap with the new operator.
  3. Return by reference what you received by reference as an argument. [EDIT: Thanks to @harshath.jr for pointing this out]

Note that when you return by value as in the code below, the compiler should optimize the assignment to avoid the copy - i.e. it will just create a single Rectangle (rect) by optimizing the create+assign+copy into a create. This only works when you create the new object when returning from the function.

Rectangle GetRect( void ) const
{
    return Rectangle( x, y, w, h );
}

Rectangle rect = theBox.GetRect();
Related Question