C ++中的数据对齐,标准和可移植性 [英] Data alignment in C++, standard and portability

查看:121
本文介绍了C ++中的数据对齐,标准和可移植性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 :: operator new(size_t)和placement c来构造类 T code> new 。

I want to construct an object of class T by using ::operator new(size_t) and placement new.

要扩展 char v [1] c $ c>,这是 T 中最后一个声明的数据成员,我分配 sizeof(T)+ n - 1 运算符new()的字节,其中 n 是以字节为单位的所需大小。这个技巧允许我访问中的任何 i v [i] -1]

To "extend" the size of char v[1], which is the last declared data member in T, I allocate sizeof(T) + n - 1 bytes with operator new(), where n is the wanted size in bytes. This trick allows me to access v[i] for any i in [0, n -1].

我的问题是关于C ++标准:

My questions are about the C++ standard:


  1. T 中数据成员声明的顺序是否反映了数据在内存中的表示顺序?

  1. Does the order of declaration of data members in T reflect the order in which data is represented in memory?

如果保存订单,则无论分配的内存大小有多大,数据成员对齐也会保留?

If the order is preserved, are data member alignments also preserved no matter how bigger is the size of the allocated memory?


推荐答案

1)是的。在关于指针比较的部分中,标准陈述指向后面成员的指针必须比指向早先成员的指针大。 修改:正如Martin所指出的,该标准仅针对POD结构强制执行此操作。

1) Yes. From the section on pointer comparisons, the standard states that pointers to later members must compare as greater than pointers to earlier members. As pointed out by Martin, the standard only mandates this for POD structs.

2)是的。数据对齐不受分配大小的影响。

2) Yes. Data alignment is not affected by the size of the allocation.

事实是,标准中没有什么可以保证使用数组的技巧这样工作(IIRC)。

The thing is, nothing in the standard actually guarantees that the trick of using arrays this way works (IIRC).

struct something {
    ...
    char buf[1];
};

但是,这是通常这样做的标准。标准人,上次我检查,正在努力的方式,他们可以编纂这些现有的做法(它已经成为C标准的方式,它只是一个时间问题,它在C ++标准化之前)。

However, this is done so commonly that it is a de-facto standard. The standards folks, last time I checked, were working on a way that they could codify these existing practices (It's already made its way into the C standard and it's only a matter of time before it's standardized in C++).

这篇关于C ++中的数据对齐,标准和可移植性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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