为什么您可以初始化常量引用,但不能初始化来自右值的非常量引用
Why can you initialize a const reference but not a non-const reference from an rvalue?
在C++中,您无法从右值初始化引用,因为右值会立即被销毁。 如何从右值初始化常量引用?
例如:
int f() {
return 3;
}
int main() {
const int& x = f(); // ok
int& y = f(); // error: invalid initialization of non-const reference of
// type ‘int&’ from an rvalue of type ‘int’
}
如果我正确理解你的问题,我想你想知道代码"const int&x = f((;"是如何工作的,因为f((的返回值将被销毁并且对该对象的引用无效。但请注意,任何函数的返回值都在编译器创建的临时变量中的堆栈上,因此它确实会保留,直到调用函数返回并且其堆栈被销毁。
相关文章:
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 为什么我可以通过引用修改常量返回
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 将常量指针引用绑定到非常量指针
- 通过常量引用传递参数的矩阵模板类
- 按值捕获引用时出现非常量
- 在C++中使用非常量引用作为常量
- 具有常量引用参数的函数模板专用化
- 多个"常量引用"变量可以共享同一个内存吗?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 为什么按值传递QStringView比引用常量更快?
- 通过引用常量函数调用另一个类的非常量函数
- 构造常量对象与引用常量对象
- 引用“常量value_type”时出错
- 为什么可以在 for 语句中重新分配引用常量
- 程序反馈:命名循环索引和引用常量数据
- 堆还是栈?在c++中函数调用中引用常量字符串时
- 为什么常量结构数组在按名称引用常量结构时不放在 .rodata 中?
- 为什么编译器允许在函数中发送对迭代器的引用,该函数引用常量迭代器