C ++中的POD类型是什么?
时间:2020-03-06 14:51:00 来源:igfitidea点击:
我已经多次遇到过这个术语POD类型。
这是什么意思?
解决方案
POD代表普通旧数据,即一个没有构造函数,析构函数和虚拟成员函数的类(无论是用关键字struct
还是关键字class
定义)。 Wikipedia上有关POD的文章更加详细,并将其定义为:
A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.
在C ++ 98/03的答案中可以找到更多详细信息。 C ++ 11更改了围绕POD的规则,大大放松了它们,因此需要在此处进行后续解答。
普通的旧数据
简而言之,它是所有内置数据类型(例如,int,char,float,long,unsigned char,double等)以及POD数据的所有聚合。是的,这是一个递归定义。 ;)
更清楚地说,POD是我们所谓的"结构":仅存储数据的一个单元或者一组单元。
非常非正式地:
POD是一种类型(包括类),在这种类型中,C ++编译器保证结构中不会发生"魔术"现象:例如,指向vtables的隐藏指针,将其转换为其他类型时应用于地址的偏移量(至少是目标的POD),构造函数或者析构函数。粗略地说,当类型中的唯一内容是内置类型及其组合时,它就是POD。结果是"类似于" C类型的行为。
不那么非正式地:
int
,char
,wchar_t
,bool
,float
,double
是POD,它们的long / short和signed / unsigned版本也是如此。- 指针(包括指向功能的指针和指向成员的指针)是POD,
- 枚举是POD
- " const"或者" volatile" POD是POD。
- POD的"类","结构"或者"联合"是POD,条件是所有非静态数据成员都是"公共"的,并且没有基类,也没有构造函数,析构函数或者虚拟方法。在此规则下,静态成员不会阻止某些东西成为POD。
- 维基百科说POD不能具有指针到成员类型的成员是错误的。或者更确切地说,这对于C ++ 98的措辞是正确的,但是TC1明确指出,指向成员的指针是POD。
正式(C ++ 03标准):
3.9(10): "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 caller 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" 9(4): "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor. Similarly a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor. 8.5.1(1): "An aggregate is an array or class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10) and no virtual functions (10.3)."
使用C ++时,Plain Old Data不仅意味着int,char等是唯一使用的类型。普通旧数据实际上意味着在实践中我们可以将其从内存中的一个位置转移到另一个位置,并且事情将按预期运行(即不会爆炸)。如果类或者类包含的任何类的成员是指针,引用或者具有虚函数的类,则这会中断。本质上,如果必须将指针包含在某个地方,则它不是普通的旧数据。