Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is_trivially_copyable behaves differently between the constructor I implemented and the default

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading