David Pickup
David Pickup

Reputation: 386

How to set the value of a boost::optional member variable in a setter method?

I can't publish my exact code, but I have a class Mike where I want it to contain a member variable of a custom object type Bob. Bob may not be set on construction of Mike, but I want it to be set later when a setter method is called. I'm trying to use a boost::optional<Bob> for this, in the following manner:

class Mike
{
  public:
    void setBob(const Bob& bob)
    {
      m_bob = bob;
    }
    boost::optional<Bob> getBob() const
    {
      return m_bob;
    }
  private:
    boost::optional<Bob> m_bob;
}

This is giving the error:

error: use of deleted function ‘Bob& Bob::operator=(const Bob&)’
     void assign_value ( argument_type val, is_not_reference_tag ) { get_impl() = val; }

I've also tried replacing the line

m_bob = bob;

with

m_bob = boost::optional<Bob>(bob);

but this results in an almost identical error.

The Bob class looks like this:

class Bob
{
  public:
    Bob(const double value) : m_value(value)
    {
    }
  private:
    const double m_value;
};

Any idea what the correct way to do this is?

Upvotes: 0

Views: 2421

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36399

The default assignment operator of Bob is deleted as it is not possible to update the value of m_value due to it being const.

There are two possible solutions:

  1. Make m_value non const. It is unusual to have a const member in a class (though perfectly valid). It would be more usual to use const Bob which would then make the member const too.
  2. Assign the new value to the optional using emplace, this destroys the old value and creates a new value instead of assigning to the old value if it exists. Depending on the exact nature of Bob this might be slightly more expensive?

    void setBob(const Bob& bob)
    {
       m_bob.emplace(bob);
    }
    

Upvotes: 1

Related Questions