POD对象向量的内存布局 [英] Memory layout of vector of POD objects

查看:81
本文介绍了POD对象向量的内存布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的C ++类

Suppose I have a simple 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个浮点数组成的数组吗?

Is it safe to assume that &v[0].data[0] points to an array of 30 floats?

推荐答案

从标准

23.3.6.1类模板矢量概述

a的元素 向量连续存储,这意味着如果v是向量,其中T是其他类型 相对于布尔,则对于所有0< = n< n,服从& v [n] ==& v [0] + n的恒等式. v.size()

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对象的开头.

so &v[0] indeed points to the beginning of 10 continuous Data objects.

但对于Data的布局,我们有

9.2.13班级成员

分配了具有相同访问控制(第11条)的(非联盟)类的非静态数据成员,因此 以后的成员在类对象中具有更高的地址.非静态数据的分配顺序 未指定具有不同访问控制的成员(11).实施一致性要求可能 使相邻的两个成员彼此不立即分配; 对以下内容的要求也可能 用于管理虚拟功能(10.3)和虚拟基类(10.1)的空间.

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个连续的浮点数是不节省的.

so we cannot be sure that sizeof(Data) == 3*sizeof(float), therefore general answer should be: it's not save to assume 30 continuous floats.

这篇关于POD对象向量的内存布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆