Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between is_trivially_copyable and is_trivially_copy_constructible?

Tags:

When would these give a different answer, and when would this difference be useful, if at all?

like image 257
rubenvb Avatar asked May 14 '13 11:05

rubenvb


People also ask

Is trivially copy constructible?

A trivially copy constructible type is a type which can be trivially constructed from a value or reference of the same type. This includes scalar types, trivially copy constructible classes and arrays of such types.

What does trivially copyable mean C++?

A trivially copyable class is a class (defined with class, struct or union) that: uses the implicitly defined copy and move constructors, copy and move assignments, and destructor. has no virtual members. its base class and non-static data members (if any) are themselves also trivially copyable types.


1 Answers

The former tests for the trivially copyable property, which in few words means that the type is memcpy-safe.

A trivially copyable class is a class that:

— has no non-trivial copy constructors (12.8),

— has no non-trivial move constructors (12.8),

— has no non-trivial copy assignment operators (13.5.3, 12.8),

— has no non-trivial move assignment operators (13.5.3, 12.8), and

— has a trivial destructor (12.4).

A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable.

[ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]

The latter tests for the presence of a trivial copy constructor, which incidentally is a requirement for the trivially copyable property. It basically implies that the copy constructor for the type performs a bitwise copy.

A copy/move constructor for class X is trivial if it is not user-provided and if

— class X has no virtual functions (10.3) and no virtual base classes (10.1), and

— the constructor selected to copy/move each direct base class subobject is trivial, and

— for each non-static data member of X that is of class type (or array thereof), the constructor selected to copy/move that member is trivial;

otherwise the copy/move constructor is non-trivial.

It is easy to fabricate a type that provides different results for these traits:

struct foo {     foo(foo const&) = default; // this is a trivial copy constructor     ~foo(); // this is a non-trivial destructor }; 
like image 146
R. Martinho Fernandes Avatar answered Sep 22 '22 19:09

R. Martinho Fernandes