std::is_trivially_copyable / std::is_trivially_copy_assignable and array wrapping classes

I am trying to wrap my head around std::is_trivially_copy_assignable<T> and std::is_trivially_copyable<T>.

As far as I understood, std::is_trivially_copy_assignable<T> checks for a trivial (non-user defined, default) copy operator, whereas std::is_trivially_copyable<T> checks to see if it safe to use memcpy on Type T. By definition, every is_trivially_copyable must be is_trivially_copy_assignable but not other way around. I hope my definitions are correct.

Now I have the following POD type class:

struct Test {
    char data[32];
    int term;
    int dummy[3];
};

When I check the following:

auto isCopyAssignTrivial = std::is_trivially_copy_assignable<Test>::value; //true
auto isCopyTrivial       = std::is_trivially_copyable<Test>::value; //true

auto isArrayCopyAssignTrivial = std::is_trivially_copy_assignable<int[2]>::value; //false
auto isArrayCopyTrivial       = std::is_trivially_copyable<int[2]>::value; //true

I got the above results.

Moreover, when I do the following, I see that anotherTestPod has its elements set correctly and It works without any problems.

Test testPod{};
for(auto &d :testPod.data) {
    d = rand() %100;
}
auto anotherTestPod = testPod;

Even though arrays are not copy assignable themselves, in the case of is_trivially_copy_assignable, how does the trivial copy assignment work?

Upvotes: 0

Views: 463

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474236

It's important to note that the rules for trivially copyability for standard-defined types (like arrays) are different from those of class types. For standard-defined types, they are trivially copyable by fiat: because the standard says that they are.

An array of elements of the type T is trivially copyable to the extent that T is trivially copyable. An array is not assignable because the standard says that arrays are not assignable. There is no contradiction because neither requires the other.

Any explicit requirement relationship between trivial copyability and assign-ability only exists for class types. And even then, C++14 permits a type to be trivially copyable if its copy assignment operator is deleted, so there isn't even a requirement of assign-ability for class types.

Upvotes: 1

Related Questions