【问题标题】:boost::optional with const membersboost::optional 与 const 成员
【发布时间】:2013-01-17 08:24:09
【问题描述】:

为什么这不起作用?

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;
}

似乎是在尝试使用赋值运算符,而不是尝试在原地构造它。我以为它会在未初始化的内存上调用 O 的复制构造函数。

/..../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

【问题讨论】:

    标签: c++ boost boost-optional


    【解决方案1】:

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

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

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

    附带说明,Optional&lt;T&gt;::reset 已弃用。您应该只使用 assingment,如

    i = O(4,5);
    

    上述语义对两者都有效。

    【讨论】:

    • 在什么情况下会用到?当我尝试分配给可选的?
    • @njr:当您分配给已经拥有值的Optional&lt;O&gt; 时,将使用赋值运算符。
    • 啊...如果我也重置两次它会失败
    • 你知道他们为什么不把它实现为调用析构函数然后再调用构造函数吗?
    猜你喜欢
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多