[C++]POD数据

2020/10 06 13:10

POD=Plain Old Data
即C语言的老布局数据

Arithmetic types (3.9.1), enumeration types, pointer types, and pointer to member types (3.9.2), and cv-qualified versions of these types (3.9.3) are collectively called scalar types. Scalar types, POD-struct types,POD-union types (clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called POD types.

C++11把POD分为2个概念集合,平凡布局(trival)和标准布局(standard layout),同时满足称为POD类型

1、拥有默认构造函数和析构函数(trival constructor, trival destructor)
2、拥有平凡的复制构造函数和移动构造函数(trival copy constructor,trival move constructor)
3、拥有平凡的复制赋值运算符和移动赋值运行符(trival assignment operator, trival move operator)
4、不能包含虚函数和虚基类

其第1、2、3可以使用=default来声明缺省版本

POD数据类型是C++为了兼容C的数据。可以使用std::is_trivial<ClassName>::value 来判断是否为trivial类型

#include <iostream>

using namespace std;

#pragma pack(1)

class Fruit 
{
};

class Stone 
{
};

class AppleA :public Fruit 
{
public:
    Fruit childFruit;
    int size;
};

class AppleB :public Fruit
{
public:
    int weight;
    Fruit childFruit;
};

class AppleC :public Fruit 
{
public:
    Fruit firstFruit;
    Stone secondStone;
    Fruit threeFruit;
    int color;
};

#pragma pack()


int main() 
{
    AppleA appleA; 
    AppleB appleB;
    AppleC appleC; 

    cout << "sizeof(appleA)=" << sizeof(appleA) << endl;
    cout << "&appleA =" << &appleA << endl;
    cout << "&appleA.childFruit=" << &appleA.childFruit << endl << endl;

    cout << "sizeof(appleB)=" << sizeof(appleB) << endl;
    cout << "&appleB =" << &appleB << endl;
    cout << "&appleB.childFruit=" << &appleB.childFruit << endl << endl;

    cout << "sizeof(appleC)=" << sizeof(appleC) << endl;
    cout << "&appleC =" << &appleC << endl;
    cout << "&appleC.firstFruit=" << &appleC.firstFruit << endl;
    cout << "&appleC.secondStone=" << &appleC.secondStone << endl;
    cout << "&appleC.threeFruit=" << &appleC.threeFruit << endl << endl;

    return 0;
}

输出:

sizeof(appleA)=5
&appleA =012FFA40
&appleA.childFruit=012FFA40

sizeof(appleB)=5
&appleB =012FFA30
&appleB.childFruit=012FFA34

sizeof(appleC)=7
&appleC =012FFA20
&appleC.firstFruit=012FFA20
&appleC.secondStone=012FFA21
&appleC.threeFruit=012FFA22

--转载请注明: http://blog.coolcoding.cn/?p=2762