简体   繁体   English

引用和常量

[英]References and constants

We can bind a reference to an object only, not to a literal or to the result of a more genreal expression. 我们只能将引用绑定到对象,而不是文字或更广义的表达式的结果。

int i=42;
double d=1.2;
int &r=10;//error:initializer must be an object.
int &r1=d; //error: initializer must be an int object

While we can bind a reference to a constant to an object, a literal and to the result of a more general expression as shown- 虽然我们可以将对常量的引用绑定到对象,文字和更通用的表达式的结果,如下所示:

int j=45;
double d=1.2;
const int &r2=j; // works
const int &r2=60; //works
const int &r3=d; //works

The reason mentioned in Primer is that the compiler creates a temporary object of type 'constant int' here. Primer中提到的原因是编译器在此处创建了一个类型为'constant int'的临时对象。

const int temp=d;
const int &r3=temp;

But if this is the case, then this logic must apply to both the above cases, and both should work if the types of reference and the object are different. 但是,如果是这种情况,则此逻辑必须同时适用于上述两种情况,并且如果引用和对象的类型不同,则两种逻辑都应起作用。 But in actual, if the types are different, then the program works only when the reference is of type 'reference to a constant' otherwise it shows an error. 但是实际上,如果类型不同,则仅当引用的类型为“对常量的引用”时,程序才能运行,否则会显示错误。 why ? 为什么呢?

Simply put: a const reference prolongs the lifetime of a temporary. 简而言之: const引用可以延长临时生存期。 It's a feature of the language to avoid dangling references that might arise from the temporary destroyed. 这是该语言的功能,可以避免因临时破坏而引起的引用晃动。

More precisely the C++ standard says: 更准确地说,C ++标准说:

[class.temporary]/p5 [class.temporary] / P5

There are three contexts in which temporaries are destroyed at a different point than the end of the fullexpression [...] The third context is when a reference is bound to a temporary. daccess-ods.un.org daccess-ods.un.org在三个上下文中,临时变量在与全表达式末尾不同的位置被销毁。第三个上下文是将引用绑定到临时对象时。

and [dcl.init.ref]/p5.2 [dcl.init.ref] /p5.2

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows: 类型“ cv1 T1”的引用由类型“ cv2 T2”的表达式初始化,如下所示:

[..lvalue and conversion cases..] [..lvalue和转换案例..]

Otherwise, the reference shall be an lvalue reference to a non-volatile const type (ie, cv1 shall be const), or the reference shall be an rvalue reference 否则,该引用应为对非易失性const类型的左值引用(即cv1为const),或者该引用应为右值引用

As for what rvalue/lvalue are, I recommend reading about value categories . 至于什么是右值/左值,我建议阅读有关值类别

Finally a word of advice if you're using MSVC: turn your warnings on for this particular issue. 最后,如果您使用MSVC,请提一个建议:针对此特定问题打开警告

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM