There was some code like this:
// Convenience to make things more legible in the following code const float & x = some.buried.variable.elsewhere; // Go on to use x in calculations...
I have been told that the ‘const float &’ is ‘bad’ and should just be a plain float or const float.
I, however, could not think of a compelling reason other than ‘you don’t have to type ‘&”.
In fact, it seems to me that in some cases the original could be better, since compiler might not allocate extra stack space to the variable.
In other words, originally I could validly say:
assert(&x == &some.buried.variable.elsewhere)
Whereas in the second case I cannot.
Also, the original seems to communicate intent better, in my view, since the whole point of a reference is to make an alias to another value.
Can anyone give me examples of where the ‘const float &’ version is worse than a plain ‘float’ or ‘const float’ in some tangible way?
I can’t think of a reason why
const float &would be better thanconst float.References make sense if you’re either worried about copies being made (which is irrelevant with a primitive type like
float) or you want to be able to update a value across all instances that share the reference (which is irrelevant withconstmembers).On top of that, references in members are a huge pain in the neck* when it comes to initialization, and so they’d have to offer a significant advantage of the alternatives in order to be useful, and it’s clearly not the case with
const float.*The FQA on references is always amusing and thought provoking