Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a reference returned from a temporary variable valid?

I've come across a situation where being able to chain a method call to a temporary variable would be really helpful:

draw(Quad(0, 0, 1, 1).rotate(90));  // <-- .rotate() returns a Quad reference

struct Quad{
    Quad(float x, float y, float width, float height){...}
    Quad & rotate(float degrees){
        ...
        return *this;
    }
}

However, I'm unsure if the temporary variable will remain alive long enough for the draw() function to use it. Is this safe to do?

like image 599
Anne Quinn Avatar asked Feb 18 '15 11:02

Anne Quinn


People also ask

Can a reference variable be returned from a method?

A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.

What happens if you return a reference?

Functions in C++ can return a reference as it's returns a pointer. When function returns a reference it means it returns a implicit pointer.

Why should we not return a reference or an address of a local variable?

The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.

Can you return a reference to a local variable?

Local variables cannot be returned by reference.


1 Answers

This particular use is safe. A temporary lasts until the end of the full-expression that creates it; here, the full-expression is the whole statement, including the call to draw.

In general, this pattern could be dangerous. The following gives undefined behaviour:

Quad & rotated = Quad(0, 0, 1, 1).rotate(90);
draw(rotated);

In my opinion, I'd prefer the type to be immutable; rather than calling a function to modify an existing object, call a const function to return a new object, leaving the existing object intact.

Unless its bound directly to a reference, which extends its lifetime to match the reference. This doesn't apply here, since it's not bound directly.

like image 191
Mike Seymour Avatar answered Oct 04 '22 02:10

Mike Seymour