3

I've recently stumbled upon a piece of which I could not say what particular sense it has; consider this:

const FVector2D L0 = (Start.LeftPos * ScaleFactor - Offset) / Size * TargetSize;
const FVector2D R0 = (Start.RightPos * ScaleFactor - Offset) / Size * TargetSize;

And:

const FVector2D& C0 = (L0 + R0) * 0.5f;

I can't see any sense in storing a calculation result into a const reference, what am I missing?

Benjamin Zach
  • 1,452
  • 2
  • 18
  • 38

1 Answers1

6

You are missing nothing indeed.

What C++ does in this case is create a temporary object with the result and then creating a reference bound to this object.

This would be suicidal (a reference bound to a temporary!) except that there is a special rule in C++ that states that in this very case the temporary object will be kept alive as long as the reference so nothing bad occurs.

Nothing particularly good either however.

6502
  • 112,025
  • 15
  • 165
  • 265
  • It can be good sometimes when the result of expression is derived type. With value, such result would slice to base, whereas with reference it would stay derived type. Was occasionally useful before `auto` was invented. – Alex Guteniev Oct 31 '17 at 13:33