c++c++11boostboost-optional

boost::optional - using boost::in_place for the object which constuctor takes other object by the reference


I try to use boost::in_place for the non-movable and non-copyable object which constructor takes other object by the reference:

struct A
{
};

struct B
{
    B(A& a): a_(a){}

    B(B const &) = delete;
    B(B&&) = delete;
    B& operator=(B const &) = delete;
    B& operator=(B&) = delete;

    A& a_;
};

int main()
{
    A a;
    boost::optional<B> op(boost::in_place(a));

    return 0;
}

The code doesn't compile: binding reference of type ‘A&’ to ‘const A’ discards qualifiers

How to fix that ?


Solution

  • Use the inplace constructor.

    In boost, this is this constructor, that takes a in_place_init_t variable, then constructs in place with the following arguments.

    boost::optional<B> op(boost::in_place_init, a);
    // Calls `B::B(A&) with `a`
    

    Or to continue using in_place, which by default takes a const reference, specify that it isn't a const reference:

    boost::optional<B> op(boost::in_place<A&>(a));