带有const成员的Boost::optional

boost::optional with const members

本文关键字:optional Boost const 成员 带有      更新时间:2023-10-16

为什么不行?

struct O {
    O(int i, int j)
        : i(i)
        , j(j)
    {}
    int const i;
    int const j;
};
int main(int argc, char** argv)
{
    boost::optional<O> i;
    i.reset(O(4, 5));
    return 0;
}

似乎在尝试使用赋值操作符,而不是尝试在适当的位置构造它。我假定它会在未初始化的内存上调用0的复制构造函数。

/..../include/boost/optional/optional.hpp:433:69: error: use of deleted function ‘O& O::operator=(const O&)’
.... error: ‘O& O::operator=(const O&)’ is implicitly deleted because the default definition would be ill-formed:
.... error: non-static const member ‘const int O::i’, can’t use default assignment operator
.... error: non-static const member ‘const int O::j’, can’t use default assignment operator

Optional使用赋值或复制构造,具体取决于i的状态。由于此状态是运行时信息,因此在赋值和复制构造之间的选择也必须在运行时做出。
然而,这意味着编译器必须为这两个选项生成代码,即使其中一个从未实际使用过。这意味着两个选项都必须是可能的。

要使代码工作,您可以向class O添加一个(总是失败的)赋值操作符:

O& O::operator=(const O&)
{
    throw "this is not possible"
    return *this;
}

作为旁注,不推荐使用Optional<T>::reset。你应该使用赋值,如

i = O(4,5);

以上描述的语义对两者都有效