它是可以移动一个boost ::可选? [英] Is it possible to move a boost::optional?
问题描述
我一直试图在一个类中定义一个默认的构造函数的举动与的boost ::可选的
成员变量。
的#include<升压/ optional.hpp>
#包括LT&;实用>
#包括LT&;矢量>结构bar {性病::矢量<&INT GT; VEC;};结构foo的{
富()=默认值;
富(富和放大器;&安培)=默认值;
推动::可选< BAR>你好;
};诠释主(){
foo的;
富B(的std ::移动(一));
}
我的编译器同时支持移动语义和违约举动构造函数,但我不能得到这个工作。
%铛++ foo.cc -std = C ++ 11 -stdlib = ++的libc
foo.cc:15:7:错误:调用'富'的构造函数中删除
富B(的std ::移动(一));
^ ~~~~~~~~~~~~
foo.cc:9:3:注意:功能已被明确标记为删除这里
富(富和放大器;&安培)=默认值;
^
产生1个错误。
块引用>有没有移动
的boost ::可选的方式
的没有的修改Boost的源$ C $ C?或者我应该等到加速支持移动?我有同样的问题,
的boost ::任何
过去。解决方案看着
的boost ::可选的
源$ C $ C,它没有定义移动构造或移动作业。但是,它定义拷贝构造函数和赋值,其中prevent从自动生成移动构造函数和赋值编译器吧。
编译器会生成隐式转移构造函数作为成员明智之举,除非你有明确定义一个拷贝构造函数或复制/移动分配或析构函数
块引用>由于吕克·丹东表明需要有针对治疗。让我们尝试使用
交换
移动的boost ::可选的
,希望创建一个空的提振::可选的
便宜,然后我们只要将默认的构造的boost ::可选的
从R值<$ C $之一C>富,例如:富(富和放大器;和b){
hello.swap(b.hello);
}和同为移动作业。
I've been trying to define a defaulted move constructor in a class with a
boost::optional
member variable.#include <boost/optional.hpp> #include <utility> #include <vector> struct bar {std::vector<int> vec;}; struct foo { foo() = default; foo(foo&&) = default; boost::optional<bar> hello; }; int main() { foo a; foo b(std::move(a)); }
My compiler supports both move semantics and defaulted move constructors, but I cannot get this to work.
% clang++ foo.cc -std=c++11 -stdlib=libc++ foo.cc:15:7: error: call to deleted constructor of 'foo' foo b(std::move(a)); ^ ~~~~~~~~~~~~ foo.cc:9:3: note: function has been explicitly marked deleted here foo(foo&&) = default; ^ 1 error generated.
Is there a way to move a
boost::optional
without modifying Boost's source code? Or should I wait until Boost supports moving?I had the same problem with
boost::any
in the past.解决方案Looking at
boost::optional
source code, it doesn't define move constructors or move assignments. However, it does define copy constructor and assignment, which prevent the compiler from auto-generating move constructor and assignment for it.the compiler will implicitly generate move constructor as member-wise moves, unless you have explicitly defined a copy constructor or copy/move assignment or a destructor
As Luc Danton suggests there needs to be a cure for that. Let's try using
swap
to moveboost::optional
in the hope that creating an emptyboost::optional
is cheap and then we just swap the default-constructedboost::optional
with the one from the r-valuefoo
, e.g.:foo(foo&& b) { hello.swap(b.hello); }
And same for the move assignment.
这篇关于它是可以移动一个boost ::可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!