There is a demonstrative code for std::is_trivially_copyable https://en.cppreference.com/w/cpp/types/is_trivially_copyable
void test()
{
struct A {
int m;
A(const A& o):m(o.m){}
};
struct D {
int m;
D(D const&) = default; // -> trivially copyable
D(int x) : m(x 1) {}
};
std::cout << std::is_trivially_copyable<A>::value << '\n';
std::cout << std::is_trivially_copyable<D>::value << '\n';
}
A is not trivially copyable, D does. I implement A's copy constructor with the default behavior. What does cause the difference?
CodePudding user response:
This is how it is defined in c : https://en.cppreference.com/w/cpp/language/copy_constructor#Trivial_copy_constructor
Trivial copy constructor The copy constructor for class T is trivial if all of the following are true:
- it is not user-provided (that is, it is implicitly-defined or defaulted) ;
- T has no virtual member functions;
- T has no virtual base classes;
- the copy constructor selected for every direct base of T is trivial;
- the copy constructor selected for every non-static class type (or array of class type) member of T is trivial;
A trivial copy constructor for a non-union class effectively copies every scalar subobject (including, recursively, subobject of subobjects and so forth) of the argument and performs no other action. However, padding bytes need not be copied, and even the object representations of the copied subobjects need not be the same as long as their values are identical.
TriviallyCopyable objects can be copied by copying their object representations manually, e.g. with std::memmove. All data types compatible with the C language (POD types) are trivially copyable.
CodePudding user response:
It is not trivial, because it is user defined. That is the rule.
The compiler is not required to figure out if your code is the same as it would have generated. That's your job to figure out. :-)