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

后端 未结 2 1500
予麋鹿
予麋鹿 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:45

    • 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 forwards the noexcept status of the special member functions of its constituent types.

      • It has variadic template-based in-place constructors and emplacement functions.

      • Defect resolutions applied to C++17 may mean that it will also forward trivial copyability of its types. That is, if all of the types are trivially copyable, then so too will variant.

提交回复
热议问题