假设我有:
#include <iostream>
#include "boost/optional.hpp"
struct cat
{
int paw = 4;
};
int main()
{
boost::optional<cat&> z;
{
cat realCat = cat();
z = realCat;
}
std::cout << z->paw << std::endl;
return 0;
}
在上面,没有理由期望打印出一致的结果,对吧,因为 realCat
是由 发布的?还是
optional
保留了 realCat
的生命?
最佳答案
不,它没有,当您尝试打印 paw
的值时,您的代码有未定义的行为.
仅当临时对象绑定(bind)到对const
的右值引用或左值引用时,C++ 生命周期延长规则才适用。 ,但是realCat
不是临时的并将其绑定(bind)到 optional
引用不会延长它的生命周期。
无论如何,这些生命周期延长规则不适用于boost::optional<T&>
. documentation对于 boost::optional
提到这个:
Rvalue references and lvalue references to const have the ability in C++ to extend the life time of a temporary they bind to. Optional references do not have this capability ...
至于std::optional
,如果您尝试创建 std::optional<T&>
,您的程序将是格式错误的.
A program that necessitates the instantiation of template
optional
for a reference type, or for possibly cv-qualified typesin_place_t
ornullopt_t
is ill-formed.
关于c++ - c++ 中的可选引用是否保留对象生命?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47983078/