c++ - C++ 编译器可以重新排序结构中的元素吗

标签 c++ struct element

C++ 编译器(特别是 g++)可以重新排序结构的内部元素吗?

我看到一些奇怪的行为,我的结构包含以下内容:

Struct SomeStruct{
   ...
   ...
   long someLong;
   long someLongArray[25];
   unsigned long someUnsignedLong;
   unsigned long someUnsignedLongArray[8];
   unsigned long int someUnsignedLongInt;
   ...
   ...
};

当我将输出写入文件时,someUnsignedLongArraysomeLongArray 的顺序似乎颠倒了(即 someLongArray[] 中的元素出现在 someUnsignedLong 之后,someUnsignedLongArray[] 的元素出现在 someLong 之后)。这可能吗??

谢谢


更新: 根据要求,我正在使用以下内容写出结构:

int fd = open(fspec,O_RDWR|O_CREAT|O_TRUNC,0666);
int writeRes =  write(fd,(char *)&someStruct,sizeof(SomeStruct));

为了完整起见,这里是完整的结构:

struct SomeStruct{
byte someByte;
byte someByteArray[6];
char someChar;
char someCharArray[5];
char someCharArrayArray[3][5];
short someShort;
signed short someShortArray[2];
unsigned short someUnsignedShort;
unsigned short someUnsignedShortArray[8];
int someInt;
int someIntArray[3];
int someIntArrayArrayArrayArray[4][3][2][6];
int *pSomeInt;
unsigned int someUnsignedInt;
unsigned int someUnsignedIntArray[9];
long someLong;
long someLongArray[25];
unsigned long someUnsignedLong;
unsigned long someUnsignedLongArray[8];
unsigned long int someUnsignedLongInt;
long long someLongLong;
long long someLongLongArray[5];
bool someBool;
bool someBoolArray[3];
unsigned long long someUnsignedLongLong;
unsigned long long someUnsignedLongLongArray[5];
unsigned long long someUnsignedLongLongArrayArray[5][2];
unsigned long long int *pSomeUnsignedLongLongInt;
};

最佳答案

它通常不能重新排序元素,不。

如果有一个访问说明符将它们分开,则异常(exception):

struct Foo {    
  A a;
  B b;
  C c;
private:
  D d;
  E e;
  F f;
};

abc保证按此顺序存储,def 保证按顺序存储。但是不能保证 abc 相对于 de 的存储位置f.

要记住的另一件事是编译器可以根据需要插入尽可能多的填充,即使它不重新排序任何内容。

这是标准的相关部分:

第 9.2.12 节:

Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1)"

关于c++ - C++ 编译器可以重新排序结构中的元素吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/916600/

相关文章:

c++ - 根据标准, "declaration of an object"到底是什么

c - typedef时重命名变量?

jquery - 使用 jQuery 将样式应用于单击元素的所有实例

CSS 父类优于其他 CSS 类

c++ - 是否可以从宏定义宏

c++ - C++ 类的 Qt 类数据成员在使用前是否应该初始化?

c++ - 在 linux 上编译一个基本的 OpenCV + Cuda 程序

struct - 如何在 Julia 中引用结构本身

c - 结构体指针在每次函数调用时都变为 NULL

swift - 如何在 Swift 中获取数组中的倒数第二个元素?