POD对象向量的内存布局
Memory layout of vector of POD objects
假设我有一个简单的 C++ class,
class Data {
public:
float data[3];
void clear() { data[0] = 0.0f; data[1] = 0.0f; data[2] = 0.0f }
}
还有一个数据向量,
std::vector<Data> v(10);
假设 &v[0].data[0]
指向 30 个浮点数的数组是否安全?
来自标准
23.3.6.1 Class template vector overview
The elements of a
vector are stored contiguously, meaning that if v is a vector where T is some type other
than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()
所以&v[0]
确实指向了10个连续Data
对象的开始。
但是对于 Data
的布局我们有
9.2.13 Class members
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).
所以我们不能确定sizeof(Data) == 3*sizeof(float)
,所以一般的答案应该是:假设30个连续的浮点数是保存不了的。
假设我有一个简单的 C++ class,
class Data {
public:
float data[3];
void clear() { data[0] = 0.0f; data[1] = 0.0f; data[2] = 0.0f }
}
还有一个数据向量,
std::vector<Data> v(10);
假设 &v[0].data[0]
指向 30 个浮点数的数组是否安全?
来自标准
23.3.6.1 Class template vector overview
The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()
所以&v[0]
确实指向了10个连续Data
对象的开始。
但是对于 Data
的布局我们有
9.2.13 Class members
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).
所以我们不能确定sizeof(Data) == 3*sizeof(float)
,所以一般的答案应该是:假设30个连续的浮点数是保存不了的。