Possible Duplicate:
Classes store data members in sequential memory?
只是想问一下为什么以下是正确的:
template<class T>
class Vec3 {
public:
// values
T x,y,z;
// returns i-th komponent (i=0,1,2) (RHS array operator)
const T operator[] (unsigned int i) const {
return *(&x+i);
}
}
或者换句话说:为什么总是保证 x, y 和 z 在内存中总是相隔 sizeof(T) 个单位。这些变量中的两个之间不能有碎片漏洞,从而让这个运算符返回一个假值吗?
不保证x
、y
和z
总是sizeof(T)
单元在内存中分开。中间可以添加填充字节。
它作为实现细节被遗漏了。
唯一可以保证的是,类/结构的开头与其 POD 结构/类的第一个成员之间没有填充。
不保证您的代码中 operator[]
的实现总是有效。
引用:
C++11: 9.2 类成员 [class.mem]
14) Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so
that later members have higher addresses within a class object. The order of allocation of non-static data
members with different access control is unspecified (11). Implementation alignment requirements might
cause two adjacent members not to be allocated immediately after each other; so might requirements for
space for managing virtual functions (10.3) and virtual base classes (10.1).