In addition to std::is_trivial
and std::is_trivially_copyable
, C++11 provides a number of type traits for checking whether types have trivial constructors, destructors and copy/move assignment operators, i.e:
std::is_trivially_constructible
std::is_trivially_default_constructible
std::is_trivially_copy_constructible
std::is_trivially_move_constructible
std::is_trivially_assignable
std::is_trivially_copy_assignable
std::is_trivially_move_assignable
std::is_trivially_destructible
What is their original intended purpose? Surely some C++ committee paper(s) must explain the rationale for their inclusion in the C++ standard library.
What is a type trait? A type trait is a simple template struct that contains a member constant, which in turn holds the answer to the question the type trait asks or the transformation it performs.
The type-traits library also contains a set of classes that perform a specific transformation on a type; for example, they can remove a top-level const or volatile qualifier from a type. Each class that performs a transformation defines a single typedef-member type that is the result of the transformation.
Why are they in the standard library? Because they're useful but impossible to implement in the language.
Two specific examples of usefulness.
std::is_trivially_copy_constructible
- If I have a vector
of a type that is trivially copy constructible, I don't need to individually copy every element when I do a reallocation. I can memcpy()
the whole block in one go. We need this type trait to check when this optimization is safe. std::is_trivially_destructible
- Trivial destruction is an important quality of a type. It's one of the criteria for it to be a literal type and thus usable in a constant expression. There are situations where I might want my type to be usable as a literal type where it is possible for that to happen (e.g. std::optional
). We need this type trait in order to make optional<T>
conditionally trivially destructible. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With