Search code examples
c++boostc++11move-semanticsboost-optional

Is it possible to move a boost::optional?


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.


Solution

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