gpt4 book ai didi

c++ - 基本类型和结构与内部只有这个基本类型的对齐

转载 作者:太空狗 更新时间:2023-10-29 21:24:13 27 4
gpt4 key购买 nike

有这段代码:

#include <iostream>

struct A {
double a;
};

int main(){
std::cout << alignof(A) << std::endl; // prints 4
std::cout << alignof(double) << std::endl; // prints 8
return 0;
}

为什么结构 A 和原始 double 类型的对齐方式不同?我正在使用 Linux 32 位。

最佳答案

我在这里找到了可能的解释:Implementation of alignof

Amazing facts about alignment

On modern x86 processors, the type double is most efficiently aligned at multiples of 8. And in fact, gcc aligns "free" doubles at multiples of 8 within stack frames. Unfortunately, ancient ABIs require that the alignment of a double within a struct is 4. The unexpected consequence is that, on x86 Linux, gcc has

  struct Double { double d; };
__alignof__ (double) == 8
__alignof__ (Double) == 4;

The same ancient ABIs specify that the size of long double is 12. Because the alignment must be a factor of the size, we have the curious situation that:

  __alignof__ (double) == 8
__alignof__ (long double) == 4;

even though long double "wants" to be at least as aligned as double.

Fortunately, it doesn't matter very much, because we never care about the alignment of types that aren't struct members.

关于c++ - 基本类型和结构与内部只有这个基本类型的对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16676722/

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