Boost logo

Boost :

Subject: Re: [boost] [optional] generates unnessesary code for trivial types
From: Fernando Cacciola (fernando.cacciola_at_[hidden])
Date: 2012-02-14 14:27:09

On 2/14/2012 3:48 PM, Krzysztof Czainski wrote:

> A note about assignment semantics:
> int i = 1, j = 2;
> optional<int&> oi = i, oj = j;
> oi = oj;
> If many people find it confusing, that oi now contains a reference to j,
> while i remains unchanged, I could live with this kind of assignment
> disabled at compile-time, and replaced by some member function.

Altough, as you would expect, I am not confused about the current rebinding
semantics (and in fact I believe is more approriate than the alternative), in
the std proposal that Andrzej and I are preparing, assignment is disabled for
optional lvalue references.

If you do need to rebind the reference, you can use the new emplace() method,
which in fact behaves consistently among all sorts of optionals, references
included and which rebinds the reference as you would expect.

OTOH, if you need to assign to the contained/referenced object instead, you can use:

(*opt) = value

which also behaves consistently among all optionals.

Finally, if you need to "assign" in a generic context where T might or might not
be a reference, but without rebinding semantics, you can do:

if ( opt )
     *opt = value ;
else opt.emplace(value)

Which also works consistently among all sorts of optional, always assign to the
contained/referenced object if it exists, or initializes the optional with a new
object/reference otherwise.


Fernando Cacciola
SciSoft Consulting, Founder

Boost list run by bdawes at, gregod at, cpdaniel at, john at