为什么一旦我将引用声明为const,那么它可以采用不同类型的数据?

Wag*_*ala 6 c++ oop

你好我想弄清楚这件事..

说我有这个代码.

int a = 5;
double& b = a; //Error.
Run Code Online (Sandbox Code Playgroud)

然后,一旦我将第二行声明为const,编译器就不会再抱怨了.

const double& b = a; //Correct.
Run Code Online (Sandbox Code Playgroud)

在幕后真正发生了什么,为什么const解决了这个问题.

jro*_*rok 7

一个int需要被转换到double第一.该转换产生临时的prvalue,并且这些不能绑定到对非const的引用.

对const的引用将延长临时的生命周期,否则将在创建它的表达式结束时将其销毁.

{
    int a = 0;
    float f = a; // a temporary float is created here, its value is copied to
                 // f and then it dies
    const double& d = a; // a temporary double is created here and is bound to 
                         // the const-ref
}   // and here it dies together with d
Run Code Online (Sandbox Code Playgroud)

如果你想知道prvalue是什么,这里有一个很好的关于价值类别的SO线程.


Jam*_*nze 6

幕后发生的事情是将int隐式转换为double.隐式转换的结果不是左值,因此它不能用于初始化非const引用.