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?
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.
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.
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.
Local variables cannot be returned by reference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With