为什么您可以初始化常量引用,但不能初始化来自右值的非常量引用

Why can you initialize a const reference but not a non-const reference from an rvalue?

本文关键字:引用 常量 初始化 非常 为什么 但不能      更新时间:2023-10-16

在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((的返回值将被销毁并且对该对象的引用无效。但请注意,任何函数的返回值都在编译器创建的临时变量中的堆栈上,因此它确实会保留,直到调用函数返回并且其堆栈被销毁。