What is the difference between std::trivially_copyable_v and std::is_pod_v (std::is_standard_layout && std::is_trivial_v)

Viewed 158

I was looking at the documentation for both of these type traits and I'm not sure what the difference is. I'm no language lawyer, but as far as I could tell, they are both valid for "memcpy-able" types.

Can they be used interchangeably?

1 Answers

No the terms cannot be used interchangeably. Both terms denote types that can be used with memcpy, and anything that's a POD is trivially copyable, but something that's trivially copyable is not necessarily POD.

In this simple example, you can see that foo is POD (and subsequently trivially copyable), while bar is not a POD, but is trivially copyable:

#include <iostream>

struct foo
{
    int n;
};

struct bar
{
    int n = 4;
};

int main()
{
    std::cout << std::boolalpha << std::is_pod<foo>() << "\n";
    std::cout << std::boolalpha << std::is_trivially_copyable<foo>() << "\n";
    std::cout << std::boolalpha << std::is_pod<bar>() << "\n";
    std::cout << std::boolalpha << std::is_trivially_copyable<bar>() << "\n";
}

The output of the above is:

true
true
false
true

Both foo and bar can be used safely with memcpy, whose documentation states:

If the objects are [...] not TriviallyCopyable, the behavior of memcpy is not specified and may be undefined.

Related