Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::is_trivially_copyable — detecting trivially copyable types

This <type_traits> trait checks at compile time whether a type is trivially copyable. Learn the equivalent ::value and _v forms and the limits of copying an object's representation.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <type_traits>
std::is_trivially_copyable<T>::value
std::is_trivially_copyable_v<T>

std::is_trivially_copyable<T> from <type_traits> is a type trait: its ::value is a Boolean constant indicating whether T is trivially copyable. std::is_trivially_copyable_v<T> exposes the same value directly. Use it in static_assert or if constexpr to check requirements in generic code.

These types include scalar types, trivially copyable classes, arrays of those types, and their cv-qualified versions. A class must have at least one eligible copy or move operation; every such eligible operation must be trivial, and its destructor must be trivial and non-deleted. This does not test standard-layout properties or merely whether a copy constructor can be called.

The precondition requires std::remove_all_extents_t<T> to be a complete type or possibly cv-qualified void. Therefore, do not query a class before its full definition. In the example, Point satisfies the trait, whereas NonTrivial does not because of its user-provided destructor.

For two distinct, existing objects of the same trivially copyable type, neither of which is a potentially-overlapping subobject, copying the entire representation with std::memcpy gives the destination the source object's value, provided the source and destination byte ranges do not overlap. Even for distinct objects, overlapping byte ranges make the std::memcpy call undefined. The example copies Point this way. However, true does not imply a portable serialization format: the representation can contain padding bytes, and pointers do not become copies of the objects they point to. Object lifetime and valid memory-access requirements still apply.

Examples

#include <cstring>
#include <iostream>
#include <type_traits>

struct Point {
    int x;
    int y;
};

struct NonTrivial {
    ~NonTrivial() {}
};

static_assert(std::is_trivially_copyable<Point>::value);
static_assert(!std::is_trivially_copyable_v<NonTrivial>);

int main() {
    Point source{3, 7};
    Point destination{0, 0};
    std::memcpy(&destination, &source, sizeof source);

    std::cout << std::boolalpha
              << std::is_trivially_copyable_v<Point> << '\n'
              << destination.x << ' ' << destination.y << '\n';
}

Result

true
3 7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources