gpt4 book ai didi

c++ - 为什么有的引用类型的变量可以绑定(bind)右值,有的不能?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:36 25 4
gpt4 key购买 nike

#include <iostream>

using namespace std;
int main() {

//int& a = 3; <- Doesn't compile. Expression must be lvalue.
const auto& c = 1 + 2; // c is a constant reference to an int. (?)
// compiles fine. 1+2 is a rvalue? what's going on?
cout << c << endl;

return 0;
}

我不明白为什么编译器不会引发编译错误。由于 auto“强制”c 成为对常量 int 的引用,并且引用被引用到左值,这是如何工作的?

最佳答案

如果没有 const,这确实无法工作——您会遇到编译错误。

但是 const 在那里,即您不会修改 c 引用的内容。

对于这种情况,标准中有额外的措辞,临时c 正在引用(1 + 2 的结果)将其生命周期延长到引用生命周期的末尾。

这与 auto 完全无关。 const 在这里产生了不同。

关于c++ - 为什么有的引用类型的变量可以绑定(bind)右值,有的不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32583791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com