我可以安全地指向重新分配的boost::optional的数据吗?

Can I safely point to the data of a reassigned boost::optional?

本文关键字:boost optional 数据 分配 安全 新分配 我可以      更新时间:2023-10-16

给定以下代码示例:

boost::optional< int > opt;
opt = 12;
int* p( &*opt );
opt = 24;
assert( p == &*opt );

是否保证断言总是有效的?

是的,这是一个保证。boost::optional<T>T逻辑上是可选对象的私有成员。

上面的代码逻辑上等价于:
bool opt_constructed = false;
int opt_i; // not constructed
new int (&opt_i)(12); opt_constructed = true; // in-place constructed
int*p = &opt_i;
opt_i = 24;
assert(p == &opt_i);
// destuctor
if (opt_constructed) {
  // call opt_i's destructor if it has one
}