std::trivially_copyable_v 和 std::is_pod_v 有什么区别 (std::is_standard_layout && std::is_trivial_v)

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

我正在查看这两种类型特征的文档,但不确定有什么区别。我不是语言律师,但据我所知,它们都适用于“memcpy-able”类型。

它们可以互换使用吗?

不,这些术语不能互换使用。这两个术语都表示可以与 memcpy 一起使用的类型,任何 POD 都可以简单复制,但是可以简单复制的东西不一定是 POD。

在这个简单的示例中,您可以看到 foo 是 POD(随后可简单复制),而 bar 不是 POD,但可简单复制:

#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";
}

上面的输出是:

true
true
false
true

foobar 都可以安全地与 memcpy, whose documentation states 一起使用:

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