C ++数据成员对齐和数组打包 [英] C++ Data Member Alignment and Array Packing

查看:228
本文介绍了C ++数据成员对齐和数组打包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码审查期间,我遇到了一些定义了如下简单结构的代码:

During a code review I've come across some code that defines a simple structure as follows:

class foo {
   unsigned char a;
   unsigned char b;
   unsigned char c;
}

在其他地方,定义了这些对象的数组:

Elsewhere, an array of these objects is defined:

foo listOfFoos[SOME_NUM];

然后,将结构原始复制到缓冲区中:

Later, the structures are raw-copied into a buffer:

memcpy(pBuff,listOfFoos,3*SOME_NUM);

此代码依赖于以下假设:a)foo的大小为3,

This code relies on the assumptions that: a.) The size of foo is 3, and no padding is applied, and b.) An array of these objects is packed with no padding between them.

我在两个平台上使用GNU进行了测试(RedHat 64b,Solaris 9),它同时工作。

I've tried it with GNU on two platforms (RedHat 64b, Solaris 9), and it worked on both.

上述假设是否有效?

推荐答案

需要一个对象数组才能创建对象。是连续的,所以在对象之间从不填充,虽然padding可以添加到对象的结尾(产生几乎相同的效果)。

An array of objects is required to be contiguous, so there's never padding between the objects, though padding can be added to the end of an object (producing nearly the same effect).

使用char的,这些假设可能是正确的,但是C ++标准肯定不能保证。一个不同的编译器,或者只是改变传递给当前编译器的标志,可能会导致在结构的元素之间或者结构的最后一个元素之后插入填充。

Given that you're working with char's, the assumptions are probably right more often than not, but the C++ standard certainly doesn't guarantee it. A different compiler, or even just a change in the flags passed to your current compiler could result in padding being inserted between the elements of the struct or following the last element of the struct, or both.

这篇关于C ++数据成员对齐和数组打包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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