Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const float & x = something; // considered harmful?

Tags:

c++

reference

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?

like image 854
jw. Avatar asked Dec 05 '22 06:12

jw.


2 Answers

I can't think of a reason why const float & would be better than const 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 with const members).

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

like image 126
Assaf Lavie Avatar answered Dec 07 '22 18:12

Assaf Lavie


You should only use references in the following cases: (If I didn't forgot one)

  1. The type being referred is not small and causes performance problems.
  2. You want your local alias to update when the value being referred to is updated.
    Or: You don't want to make a copy.
  3. You want the ability to update the other value. (In case it is not constant)

So in this case the float is small enough, you probably don't want it to update when the value being referenced to updates (causing problems in your calculations) and since you are using constants you don't want it to update.

So, you would want:

const float x = some.buried.variable.elsewhere;
like image 32
Tamara Wijsman Avatar answered Dec 07 '22 18:12

Tamara Wijsman