
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; };
Not quite. Your code has errors: (1) constructValue takes SomeType& while it should boost::optional< SomeType
&.
(2) constructValue must not be const since it is static. (3) constructValue must not be static in the first place anyway, since it calls member function "virtualFunction". But those are just minor issues. The approach by itself does work. I realized that when answering to "Andrey Semashev" and already applied to solution to my code. In fact your proposition is even somewhat better than mine by encapsulating entire construction process in a single function and calling in_place copy constructor rather than ordinary constructor. Thanks! Adam Badura