Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : has_trivial_X type traits

Tags:

c++

types

c++11

The boost library, and it seems the upcoming C++0x standard, define various type trait templates to differentiate between objects which have trivial constructors, copy constructors, assignment, or destructors, versus objects which don't. One of the most significant uses of this is to optimize algorithms for certain types, e.g. by using memcpy.

But, I don't understand the real practical difference between all the various has_trivial_X templates. The C++ standard only defines two broad categories of types that concern us here: POD and non-POD. A type is non-POD if it has a defined constructor, copy constructor, assignment operator, or destructor. In other words, anything that's not a built-in type, or a C-struct of built-in types, is not a POD.

So what's the point of differentiating between, for example, has_trivial_assign and has_trivial_constructor? If an object has a non-trivial assignment operator OR a non-trivial constructor it's not a POD. So under what circumstances would it be useful to know that an object has a trivial assignment operator, but a non-trivial constructor?

In other words, why not define a single type-trait template, is_pod<T>, and be done with it?

like image 606
Charles Salvia Avatar asked Oct 05 '09 10:10

Charles Salvia


1 Answers

The POD type definition got relaxed in C++0A.

A type may have a non-trivial-constructor, but may have a trivial assignment operator.

E.g.

struct X
{
    X() : y( -1 ) {}
    X( int k, int v ) : y( k * v ) {}

    int y;
};

X could be 'memcopy'-ied, but not trivially constructed.

like image 122
Christopher Avatar answered Nov 19 '22 17:11

Christopher