Is it possible to move a boost::optional?

拈花ヽ惹草 提交于 2019-12-01 02:42:22
Maxim Egorushkin

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.

Boost.Optional supports move construction only since Boost version 1.56. See the release notes.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!