有什么区别:
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.
更多推荐
发布评论