Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rationale for type traits checking triviality of class special functions

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.

like image 881
jotik Avatar asked Feb 20 '17 20:02

jotik


People also ask

What are type traits?

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.

How do type traits work c++?

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.


1 Answers

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.
like image 140
Barry Avatar answered Oct 03 '22 06:10

Barry