我尝试将 boost::in_place 用于构造函数通过引用获取其他对象的不可移动和不可复制的对象:
struct A
{
};
struct B
{
B(A& a): a_(a){}
B(B const &) = delete;
B(B&&) = delete;
B& operator=(B const &) = delete;
B& operator=(B&) = delete;
A& a_;
};
int main()
{
A a;
boost::optional<B> op(boost::in_place(a));
return 0;
}
代码无法编译:将“A&”类型的引用绑定(bind)到“const A”会丢弃限定符
如何解决?
最佳答案
使用就地构造函数。
在 boost 中,这是 this constructor ,它采用 in_place_init_t
变量,然后使用以下参数进行构造。
boost::optional<B> op(boost::in_place_init, a);
// Calls `B::B(A&) with `a`
或者继续使用 in_place
,它默认采用 const 引用,指定它不是 const 引用:
boost::optional<B> op(boost::in_place<A&>(a));
关于c++ - boost::optional - 将 boost::in_place 用于构造函数通过引用获取其他对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55483449/