11

What should I do to initialize boost::optional< T > if underlying type T is non-default constructible, non-copyable/moveable, but one's instance still can exist?

Is it forbidden for boost::optional by any semantic reasons to have some member function like template< typename... Args > boost::optional< T >::construct(Args && ...args), that delivers all the arguments to in-place operator new to construct the object entirely (for non-ref type T)? Variant is to have non-member function like std::make_shared< T >.

It seems to me, that my problem can be solved by means of using of std::unique_ptr/std::shared_ptr, but in this case my question is: "Why boost::optional progress is frozen?".

Tomilov Anatoliy
  • 15,657
  • 10
  • 64
  • 169

1 Answers1

17

boost::optional can be initialized with a non-copyable type by using in-place factories.

Specifically, you can use them like this:

#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>

class MyType : private boost::noncopyable
{ 
public:
  MyType(T1 const& arg1, T2 const& arg2);
}
...
boost::optional<MyType> m_var;
...
m_var = boost::in_place(arg1, arg2);
...

In C++14 there is a proposed std::make_optional that would be a better solution to this problem. However, this has not been implemented in Boost.Optional.

Martin Ba
  • 37,187
  • 33
  • 183
  • 337
Jephir
  • 1,331
  • 17
  • 16
  • 1
    what if it is default constructible? Is there a way to construct a noncopyable boost::optional without boost::in_place? my various attempts have failed to compile – Geronimo Sep 27 '17 at 18:44
  • If it is a default constructable - call boost::in_place without arguments: Foo foo; foo = boost::in_place(); – Vladislav Feb 04 '19 at 13:38