Boost logo

Boost :

Subject: Re: [boost] [optional] Types without assignment operator
From: Adam Badura (abadura_at_[hidden])
Date: 2012-11-14 07:11:31


> >
> > So instead of accessing the object directly I always access it by a
> > function. That function first checks if the object is already
> > constructed
> > (boost::optional is initialized) and if so just returns it. Otherwise it
> > first constructs it.
> >
>
> I am having problems imagining the situation. Can't you change your
> function so that returns real object rather than optional object if it is
> initialized? Perhaps using optional reference to an object would solve
> your
> problem?

Example follows:

>>>>>>>>>>

class Owner {
public:
    Owner()
        : m_value()
    {
    }

    SomeType const& getValue() const {
        if ( !m_value )
            m_value = constructValue();
        return *m_value;
    }

protected:
    virtual int virtualFunction() const = 0;

private:
    SomeType constructValue() const {
        SomeType object( /*...*/ );
        object.callThis();
        object.assignHere = virtualFunction();
        return object;
    }

    mutable boost::optional< SomeType > m_value;
};

<<<<<<<<<<

Now SomeType does not support copying by assignment but it does support copy
construction. It might be silly or maybe not. It does not matter since it is
not my type and I have to deal with it (it is
boost::program_options::options_description).

I cannot construct m_value in Owner constructor since (as can be seen in
"constructValue" function) it requires a virtual call (to
"virtualFunction"). Also note that "constructValue" is not just a simple
construction.

Obviously I could avoid the problem by not storing "m_value" in first place.
But for other reasons (like for example efficiency, but not only) I would
like to store it.

Adam Badura


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk