I\'ve been trying to define a defaulted move constructor in a class with a boost::optional
member variable.
#include
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.
See Move constructor — Q&A:
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 move boost::optional
in the hope that creating an empty boost::optional
is cheap and then we just swap the default-constructed boost::optional
with the one from the r-value foo
, e.g.:
foo(foo&& b) {
hello.swap(b.hello);
}
And same for the move assignment.
It's not clear how high on the agenda C++11 feature support for boost::optional is.
I found a nice fellow on the Internet who gave me some of his own code under a boost license...which is still undergoing some tweaks. It's at a point where it works for me. Maybe it will help anyone looking at this question:
https://github.com/hostilefork/CopyMoveConstrainedOptional
There is also a larger group effort to define a std::optional
which has been going on...but their reference implementation wasn't able to handle some of the cases I had:
http://kojot.sggw.waw.pl/~akrzemi1/optional/tr2.optional.proposal.html
Boost.Optional supports move construction only since Boost version 1.56. See the release notes.