对于函数 T& f() {...}
,在 T x = f();
中创建的引用实体的生命周期是多长?
根据标准“引用的生命周期从其初始化完成时开始,结束时就好像它是一个标量对象一样。”,虽然有一个部分涉及临时对象,但引用不是对象,因此它不' 似乎适用。
这是否意味着根据标准,在上面的示例中,引用实际上必须存在于 T x = f();
所在的整个作用域 block 中?这似乎是多余的。
如果此处的引用与“临时”对象的处理方式类似,我看不出有任何问题 - 它在包含它的完整表达式的末尾停止存在似乎是安全的。
最佳答案
Does this mean that according to the standard, in the example above the reference must actually exist throughout the whole scope block in which
T x = f();
lies?
是的,表达式 f()
的类型实际上是 T
而不是 T&
(因为在 C++ 中表达式的类型永远不会引用类型),因此您实际上并不是在创建引用变量 x
,而是创建一个普通的非引用 变量 x
。因此,正常的范围规则适用。
基本上,x
正在使用引用引用的值进行初始化。 来自 expression's documentation
Each expression has some non-reference type, and each expression belongs to exactly one of the three primary value categories: prvalue, xvalue, and lvalue.
例如,
int& f()
{
static int i = 0;
return i;
}
int main()
{
{
int x = f(); //x is a copy of i
//you can use x here in this block
}//scope of x ends
//can't use x here
}
关于c++ - 从函数返回的引用的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74072237/