Boost logo

Boost :

From: Jaap Suter (J.Suter_at_[hidden])
Date: 2003-10-26 16:24:14


Hello,

I was wondering if it would be possible to provide a method for in-place
construction into a Boost variant, to avoid copy construction.

For example:

    boost::variant<foo, bar> v;
    bar b;
    v = b; // copy constructs b into v, first destroying the old foo.
    v.construct<bar>(); // default constructs a bar into v;
    v.construct<bar>(3.14f); // constructs a bar into v using the
constructor that takes one float;

I am using Boost variant in a state-machine implementation, where each type
in the variant represents a possible state. I'm using constructors and
destructors as state entry and exit functions, but because of the way
objects have to be assigned to variants, this scheme falls apart because of
the copy-construction happening. If I could do an in-place construction of
the next-state, my problems would be solved. Consider the following snippet:

    struct state_0 : noncopyable
    {
        state_0() { cout << "state 0 entered\n"; }
        ~state_0() { cout << "state 0 exit\n"; }
    };

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

    int main()
    {
        variant<state_0, state_1> state_machine;
        state_machine.construct<state_1>();
    }

Output:

    state 0 entered
    state 0 exit
    state 1 entered
    state 1 exit

Without the in-place construction, the above can possibly look as:

    int main()
    {
        variant<state_0, state_1> state_machine;
        state_machine = state_1();
    }

Output:

    state 0 entered
    state 1 entered
    state 0 exit
    state 1 copy ctor
    state 1 exit
    state 1 exit

Which is obviously not desirable... :).

Notice that my suggestion implies that it would become possible to put
non-copy-constructible objects into boost::variant. Perhaps, if the above
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).

Thanks,

Jaap Suter


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