在复制初始化中是否返回对本地对象未定义行为的引用?
Is returning a reference to a local object undefined behavior in copy initialization?
考虑以下代码:
struct foo
{
foo(foo const&) = default; // To make sure it exists
};
foo& get_local_foo_reference()
{
foo my_local_foo;
return my_local_foo; // Return a reference to a local variable
}
int main()
{
foo my_foo = get_local_foo_reference();
}
现在每个人都会同意返回对局部变量的引用是不好的并且会导致未定义的行为。
但是在参数 copy initialization (as shown in the code above) the argument is a constant lvalue reference, so it should be a reference initialization 的情况下,它延长了引用的生命周期。
这是有效的,还是仍然是未定义的行为?
生命周期延长仅适用于 temporaries (and subobjects thereof)。 my_local_foo
不是临时的。
生命周期扩展仅适用于绑定到 const 引用或右值引用时的临时对象。 (临时不能绑定到非 const 左值引用)
即使你return临时的,也是UB:
const foo& create_foo() { return foo{}; } // Also UB
来自http://eel.is/c++draft/class.temporary#6.10:
The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
考虑以下代码:
struct foo
{
foo(foo const&) = default; // To make sure it exists
};
foo& get_local_foo_reference()
{
foo my_local_foo;
return my_local_foo; // Return a reference to a local variable
}
int main()
{
foo my_foo = get_local_foo_reference();
}
现在每个人都会同意返回对局部变量的引用是不好的并且会导致未定义的行为。
但是在参数 copy initialization (as shown in the code above) the argument is a constant lvalue reference, so it should be a reference initialization 的情况下,它延长了引用的生命周期。
这是有效的,还是仍然是未定义的行为?
生命周期延长仅适用于 temporaries (and subobjects thereof)。 my_local_foo
不是临时的。
生命周期扩展仅适用于绑定到 const 引用或右值引用时的临时对象。 (临时不能绑定到非 const 左值引用)
即使你return临时的,也是UB:
const foo& create_foo() { return foo{}; } // Also UB
来自http://eel.is/c++draft/class.temporary#6.10:
The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed at the end of the full-expression in the return statement.