Search code examples
c++chainingobject-lifetime

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?


Solution

  • 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.