Boost logo

Boost :

From: Brian McNamara (lorgon_at_[hidden])
Date: 2003-10-26 17:31:28


On Sun, Oct 26, 2003 at 01:24:14PM -0800, Jaap Suter wrote:
> boost::variant<foo, bar> v;
> bar b;
> v = b; // copy constructs b into v, first destroying the old foo.

The word "first" above bothers me.

I can see why, in your particular application, it is useful to "first
destroy the old value, then construct the new value". However I think
this implies that variants give up the "strong" exception guarantee.
(Actually I have lost track of if variant currently gives the strong
guarantee; if not, my point is moot.)

> struct state_1 : noncopyable
> {
> state_1() { cout << "state 0 entered\n"; }
> state_1() { cout << "copy ctor"; }
> ~state_1() { cout << "state 0 exit\n"; }
> };

I think you meant to say

> struct state_1
> {
> state_1() { cout << "state 1 entered\n"; }
> state_1(const state_1&) { cout << "copy ctor"; }
> ~state_1() { cout << "state 1 exit\n"; }
> };

> Notice that my suggestion implies that it would become possible to put
> non-copy-constructible objects into boost::variant. Perhaps, if the above

This does seem to be a useful capability. The ordering is an issue,
though (e.g. is it "first construct the new value, then destroy the old
value" or vice versa). This directly affects a lot of the recent
discussion about variant's implementation, I think.

> suggestion is considered too esoteric, somebody can think of a scheme that
> allows me to do the above, without using dynamic memory allocations (the
> whole reason I'm using variant in the first place).

Do all of your state types have nothrow constructors? If the call to
   v.construct<T>(args)
is calling a nothrow constructor, then the "destroy, then create"
ordering can still preserve the strong guarantee, it seems.

There was a lot of discussion about variant and issues related to this a
month or two ago, but I lost track of where things finally ended up. :)

-- 
-Brian McNamara (lorgon_at_[hidden])

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