将int分配给double&

我想了解为什么这不能编译:

int main()
{
    int a = 1;
    double& b = a;
    std::cout << b;
}

使用double const& b = a而不是double& b = a工作正常。

回答

Adouble和 anint有不同的对齐要求和不同的内存表示。通过另一种类型的眼睛将变量作为一种类型读取也会使您的程序具有未定义的行为。

当你做类似的事情时

int a = 1;
double b = a;  // note, not a reference

thena被隐式转换为一个临时的double,然后分配给b. 如果你这样做

double& b = a;

然后b尝试引用该临时文件double,这是无效的,因为临时文件将在表达式结束时被销毁。

但是,您可以通过使用const&. 然后,临时对象的生命周期将延长到引用生命周期的末尾(范围的末尾)。

例子:

const double& b = a; // valid, but usually pointless

关于您对问题的补充:

使用double const& b = a而不是double& b = a工作正常

那只是因为“标准是这样说的”。非const&临时性意味着您想要对该临时性进行更改 - 这通常是一个错误,在这些情况下您可能需要 adouble而不是 a double&

  • To extend the subtle difference, `int a = 5; int const& b = a; a = 6;` now b is also 6. `int a = 5; double const& b = a; a = 6;` but b is still 5.0 since it is an alias to the unnamed temporary.

以上是将int分配给double&amp;的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>