
2012/11/14 Adam Badura <abadura@o2.pl>
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; };
<<<<<<<<<<
Would the following work for you? class Owner { public: Owner() : m_value() {} SomeType const& getValue() const { if ( !m_value ) constructValue(m_value); return *m_value; } protected: virtual int virtualFunction() const = 0; private: static void constructValue(SomeType & target) const { SomeType object( /*...*/ ); object.callThis(); object.assignHere = virtualFunction(); target = boost::in_place(object); } mutable boost::optional< SomeType > m_value; };