What are the differences between std::variant and boost::variant?

后端 未结 2 1497
予麋鹿
予麋鹿 2020-12-06 09:52

In an answer to this SO question:

What is the equivalent of boost::variant in the C++ standard library?

it is mentioned that boost::variant and

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 10:31

    It seems the main point of contention regarding the design of a variant class has been what should happen when an assignment to the variant, which should upon completion destory the old value, throws an exception:

    variant v = "ABC";
    v = MyClassWithThrowingDefaultCtor();
    

    The options seem to be:

    • Prevent this by restricting the possible representable types to nothrow-move-constructible ones.
    • Keep the old value - but this requires double-buffers (which is what boost::variant does apparently).
    • Have a 'disengaged' state with no value for each variant, and go to that state on such failures.
    • Undefined behavior
    • Make the variant throw when trying to read its value after something like that happens

    and if I'm not mistaken, the latter is what's been accepted.

    This is summarized from the ISO C++ blog post by Axel Naumann from Nov 2015.

提交回复
热议问题