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

大城市里の小女人 提交于 2019-11-28 00:45:01
  • Assignment/emplacement behavior:

    • boost::variant may allocate memory when performing assignment into a live variant. There are a number of rules that govern when this can happen, so whether a boost::variant will allocate memory depends on the Ts it is instantiated with.

    • std::variant will never dynamically allocate memory. However, as a concession to the complex rules of C++ objects, if an assignment/emplacement throws, then the variant may enter the "valueless_by_exception" state. In this state, the variant cannot be visited, nor will any of the other functions for accessing a specific member work.

      You can only enter this state if assignment/emplacement throws.

  • Boost.Variant includes recursive_variant, which allows a variant to contain itself. They're essentially special wrappers around a pointer to a boost::variant, but they are tied into the visitation machinery.

    std::variant has no such helper type.

  • std::variant offers more use of post-C++11 features. For example:

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<std::string, MyClassWithThrowingDefaultCtor> 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!