C++ Data Member Alignment and Array Packing(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,并且没有应用填充,并且 b.) 这些对象的数组被打包,它们之间没有填充.
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.
我已经在两个平台(RedHat 64b、Solaris 9)上用 GNU 尝试过它,它在两个平台上都有效.
I've tried it with GNU on two platforms (RedHat 64b, Solaris 9), and it worked on both.
上述假设是否有效?如果没有,在什么条件下(例如操作系统/编译器发生变化)可能会失败?
Are the assumptions above valid? If not, under what conditions (e.g. change in OS/compiler) might they fail?
推荐答案
对象数组必须是连续的,所以对象之间永远不会有填充,尽管填充可以添加到对象的末尾(产生几乎效果一样).
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).
鉴于您正在使用字符,假设通常是正确的,但 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++ 数据成员对齐和数组打包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 数据成员对齐和数组打包
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07