引用函数的 return 值
Reference to return value of function
我很困惑在下面的代码片段中是否保证 foo
有效,即是否允许我将函数 return 值存储为 const 引用?
我问是因为 return 值存储在堆栈框架中,该值在 returned 后不久可能无效。
Foo getFoo() {
return Foo();
}
void bar() {
const auto& foo = getFoo();
// more function calls...
// is foo guaranteed to be valid?
}
它是有效的 C++,但请注意 一些编译器(据我所知,例如 Visual Studio 2015)不实现它正确.
根据标准(N4140
):
12.2 Temporary objects
....
4 There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when a default constructor is called to initialize an element of an array. If
the constructor has one or more default arguments, the destruction of every temporary created in a default
argument is sequenced before the construction of the next array element, if any.
5 The second context is when a reference is bound to a temporary. The temporary to which the reference is
bound or the temporary that is the complete object of a subobject to which the reference is bound persists
for the lifetime of the reference except:
(some exceptions)
我很困惑在下面的代码片段中是否保证 foo
有效,即是否允许我将函数 return 值存储为 const 引用?
我问是因为 return 值存储在堆栈框架中,该值在 returned 后不久可能无效。
Foo getFoo() {
return Foo();
}
void bar() {
const auto& foo = getFoo();
// more function calls...
// is foo guaranteed to be valid?
}
它是有效的 C++,但请注意 一些编译器(据我所知,例如 Visual Studio 2015)不实现它正确.
根据标准(N4140
):
12.2 Temporary objects
....4 There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when a default constructor is called to initialize an element of an array. If the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.
5 The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
(some exceptions)