gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:04:06 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com