Subject: [boost] [optional] Types without assignment operator
From: Adam Badura (abadura_at_[hidden])
Date: 2012-11-14 06:39:26
I use boost::optional for deferred construction.
Something similar to the idea described in "Bypassing expensive unnecessary
default construction" in Boost.Optional documentation. Only in my case I do
this because the mentioned construction requires virtual function calls and
this cannot be done in owning object constructor and has to be postponed.
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.
That approach requires only copy construction (or even move construction if
boost::optional would support moving in the first place). Yet due to
implementation details the embedded type has to be assignable as well. Even
thou assignment operator will never be called (in this scenario).
Is there a way to avoid this issue?
If not then how about adding a function like "assign" (possibly named
otherwise or with additional defaulting argument) which could assign by
first destroying old object (if any) and then copy/move constructing a new
This would obviously be bad from exception safety (guarantees) point of
view, but well... don't call the function if you don't like that. And in
scenarios like mine it would not be an issue since there would be no object
to destroy anyway. (Also the function could assert/throw on that
Now the Synopsis part of the Boost.Optional documentation does mention
(Typed)InPlaceFactory assign operators which do look promising for solving
this issue. But firstly they are not documented in following Detailed
Semantics part. There is even no link in the Synopsis. (Is this docs bug? In
which part? Missing docs or extra functions?) And secondly
(Typed)InPlaceFactory support is "intrusive". I cannot add it to a class
without changing the class itself. And in my case I cannot change the class
(boost::program_options::options_description - why cannot it be copy
assigned, that I don't know...). Maybe adding some extra wrapper would help
but I don't think it would be a solution. Rather a somewhat ugly workaround.