Boost logo

Boost Users :

Subject: Re: [Boost-users] [variant] Efficiency
From: Maxim Koshelev (chuchelo_at_[hidden])
Date: 2009-06-17 06:26:10


In common case it is not compiller solution due to complexity of
constructors/destructors of holded class.

variant<A,B> v( B() );

this code MUST call constructor of class B two times. First time when
B is created, second time when just created instance of B copyied to
variant. Valid solution is use type-traits. Something like:

variant<A,B> v( Trait<B>())

where Trait is empty class with typedefs

On Tue, Apr 21, 2009 at 6:25 PM, Igor R<boost.lists_at_[hidden]> wrote:
>> there is great disadvantage of variant in performance terms. One can't
>> create instance of variant with proper type inside without calling
>> copy costructor.
>
> I think this depends on your compiler/optimizer. The following test
> code was compiled with MSVC9, release mode (/O2 /Ob2 /Oi /Ot /Oy /GL),
> see comments inside the code:
>
> int main()
> {
>        struct A
>        {
>                      A() : a_(1)
>                      {}
>          int a_;
>        };
>        struct B
>        {
>                      B() : b_(2.0)
>                      {}
>          double b_;
>        };
>        struct Visitor : boost::static_visitor<>
>        {
>                void operator()(const A &a) const
>                {       std::cout << a.a_; }
>                void operator()(const B &b) const
>                {       std::cout << b.b_; }
>
>                void operator()(int i) const
>                {       std::cout << i; }
>                void operator()(const std::string &s) const
>                {       std::cout << s; }
>        };
>
>        B b;
>        boost::variant<A, B> v(b);
>                    // the previous construction compiled into 1
> instruction (even a call to the constructor was optimized out):
>                    // movsd       xmm0,mmword ptr
> [__real_at_4000000000000000 (41FD68h)]
>
>        boost::apply_visitor(Visitor(), v);
>
>        std::string s = "abcd";
>
>        boost::variant<int, std::string> v1(s);
>                    // the previous construction compiled into a
> direct call to variant::make_initializer_node::initialize(),
>                    // which in turn calls basic_string::assing() - that's all.
>
>        boost::apply_visitor(Visitor(), v1);
> }
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net