问题描述
有一些代码如下:
//方便在以下代码中使事情更清晰
const float& x = some.buried.variable.elsewhere;
//继续在计算中使用x ...
已被告知,const float&是坏,应该只是一个普通的浮点或const浮点。
然而,我不能想到一个令人信服的理由,除了你不必类型'&'。
事实上,在某些情况下,原来可能更好,因为编译器可能不会分配额外的堆栈空间给变量。
换句话说,最初我可以有效地说:
assert(& x ==& some.buried.variable.elsewhere)
此外,在我看来,原来似乎更好地沟通意图,因为引用的整个点是将一个别名替换为另一个值。 / p>
任何人都可以告诉我们const float&版本比一个简单的float或const float更有效?
const float&
会优于 const float
。
如果你担心副本是否生效(这与原始类型无关,例如 float
),或者您希望能够在所有共享引用的实例(与 const
成员无关)中更新值。
除此之外,成员中的引用在初始化时是一个巨大的痛苦,所以他们必须提供一个显着的优势,以便有用的替代品,显然不是 const float
的情况。
*
总是有趣和引人注目的
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 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
这篇关于const float& x = something; //认为有害?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!