c++中的pod类型

转:http://hi.baidu.com/cindyylxx/item/8a93f409e5a4d9e1ff240da4

最早看到POD(plain old data)类型,是在imperfect c++里。我觉得这是一本把我带到c++世界里的一本很重要的书。

书里是这样解释POD的:

1、   所有标量类型(基本类型和指针类型)、POD结构类型、POD联合类型、以及这几种类型的数组、const/volatile修饰的版

        本都是POD类型。

2、 POD结构/联合类型:一个聚合体(包括class),它的非static成员都不是pointer to class member、

        pointer to class member function、非POD结构、非POD联合,以及这些类型的数组、引用、const/

        volatile修饰的版本;

        并且,此聚合体不能有用户自定义的构造函数、析构函数、拷贝构造函数.

3、 POD类型可以具有static成员、成员typedef、嵌套struct/class定义和 成员函数/方法。

(C++标准)给出的定义:

将对象的各字节拷贝到一个字节数组中,然后再将它重新拷贝到原先的对象所占的存储区中,此时该对象应该具有它原来的值。

POD类型的特点:

所有POD类型都可以作为union的成员,反之,所有非POD类型都不能作为union的成员。

POD特性利用:

我们可以利用POD类型特性来判断一个类型是否为POD类型:

template<class T> struct must_be_pod

{

    union

    {

        T noname;

    };

};

这个模板的意思是,只要类型T是非POD类型,那么编译器将报错,因为T被作为了union的一个成员。

VS2008里的测试代码如下:

class A

{

public:

A(){}

void f() { cout << "A::F" << endl; }

protected:

private:

int i;

int j;

};

template<class T> struct must_be_pod

{

union

{

    T noname;

};

};

must_be_pod<A> a; 编译器会报错:1>member 'must_be_pod<T>::noname' of union 'must_be_pod<T>::<unnamed-tag>' has user-defined constructor or non-trivial default constructor

其实POD本质就是与c兼容的数据类型。

-----------------------------------------------------------

还有一篇资料:http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html

原文地址:https://www.cnblogs.com/Clingingboy/p/3044454.html