C ++常量引用和常量之间的区别?(Difference between C++ const references and consts?)

编程入门 行业动态 更新时间:2024-10-24 06:28:19
C ++常量引用和常量之间的区别?(Difference between C++ const references and consts?)

有什么区别:

const double& pi = 3.14;

和(无&符号):

const double pi = 3.14;

它们都具有相同的L和R值,所以它们有什么区别? 谢谢。

What is the difference between:

const double& pi = 3.14;

and (no ampersand):

const double pi = 3.14;

They both seem to have the same L and R values so what is the difference?

最满意答案

对于您的特定示例,没有区别。

这意味着,无论如何,无法将它们分开。

然而,由于第一个绑定引用临时,当类型是类类型时,临时可以是派生类,例如由函数产生! 然后在范围的末尾正确调用它的析构函数。 在ScopeGuard实现中使用这个小巧的技巧(参见DDJ中的原始ScopeGuard文章 ,由Petru Marginean和Andrei Alexandrescu-Petru发明了ScopeGuard,而Andrei做出了更一般的东西)。

我曾问过创建C ++语言的Bjarne Stroustrup,为什么您的第一个声明中的语法被支持。

他的回答是,它主要是制定统一的规则(即不要为本地引用做任何特殊的例外,而不是引用作为形式参数)。 我想当时我们都不熟悉ScopeGuard。 回想起来很简单,但需要Petru或Andrei的头脑才能想出类似的东西! :-)

干杯&hth。

For your particular example there's no difference.

And that means, no way to tell them apart, whatsoever.

However, since the first binds a reference to a temporary, when the type is of class type the temporary can be of a derived class, e.g. produced by a function! And it then has its destructor properly called at the end of the scope. This little el neato trick is used in ScopeGuard implementations (see the original ScopeGuard article in DDJ, by Petru Marginean and Andrei Alexandrescu -- Petru invented ScopeGuard and Andrei made a more general thing on top).

I once asked Bjarne Stroustrup, who created the C++ language, why the syntax in your first declaration is supported.

And his reply was that it was mostly to have uniform rules (i.e. to not make any special exception for local references as opposed to references as formal parameters). I think at that time neither of us were familiar with ScopeGuard. It's simple in retrospect, but it takes a mind like Petru's, or Andrei's, to come up with something like that! :-)

Cheers & hth.

更多推荐

本文发布于:2023-07-23 02:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   区别   Difference   consts   references

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!