Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 799
Rish Avatar asked Sep 15 '25 09:09

Rish


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.

like image 71
Tas Avatar answered Sep 17 '25 01:09

Tas