带有const成员的Boost::optional
boost::optional with const members
为什么不行?
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);
以上描述的语义对两者都有效
相关文章:
- boost 是否有按特殊类型值编码状态"compact optional"?
- 如何正确地将 boost::optional<std::chrono::d uration> 作为函数参数?
- 我已经编写了C++代码将 boost::optional 视为一个范围,但它无法编译
- 将 std::vector<boost::optional<double>> 转换为 std::vector<double>
- 为什么 boost::optional::is_initialized() 被弃用了?
- 如何将构造函数参数转发到 boost::optional
- 如何在 setter 方法中设置 boost::optional 成员变量的值?
- boost::any_cast 和 std::optional's
- 使用带有 boost::optional" 参数与 boost::spirit 绑定成员函数
- boost::optional<std::string> 和来自 char[] 的隐式构造函数
- boost::optional<>如何处理局部变量?
- 如何包装返回 boost::optional 的 C++ 函数<T>?
- 无法构建 Boost 1.59 错误:功能 "deduced-address-model" : "32" "64" : "propagated" "optional" "composite" "hid
- 如何将boost::optional设置回未初始化状态
- 我可以安全地指向重新分配的boost::optional的数据吗?
- Boost python optional抛出错误
- 使用boost::optional时避免使用temporary
- 从boost::optional中检索对象
- 使用boost::optional失败
- 使用boost::optional捕获和包装异常