c++ - GCC 中的结构对齐(是否应在 typedef 中指定对齐?)

标签 c++ gcc alignment

抱歉问了一个愚蠢的问题,但如果我需要确保结构/类/union 的对齐,我应该在 typedef 声明中添加 attribute((aligned(align))) 吗?

class myAlignedStruct{} __attribute__ ((aligned(16)));
typedef myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?

最佳答案

should I add attribute((aligned(align))) to typedef declaration?

不...typedef 只是指定的实际类型的假名或别名,它们不作为具有不同对齐、包装等的单独类型存在。

#include <iostream>

struct Default_Alignment
{
    char c;
};

struct Align16
{
    char c;
} __attribute__ ((aligned(16)));

typedef Align16 Also_Align16;

int main()
{
    std::cout << __alignof__(Default_Alignment) << '\n';
    std::cout << __alignof__(Align16) << '\n';
    std::cout << __alignof__(Also_Align16) << '\n';
}

输出:

1
16
16

关于c++ - GCC 中的结构对齐(是否应在 typedef 中指定对齐?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6786138/

相关文章:

c++ - 如何用c++求公因数?

c++ - 使用计时器在带有 C++ 的 Windows Metro 中触发事件

c++ - 为什么 'simplified' 代码没有向量化

c++ 程序在一个线程发生访问冲突时终止 - 如何在 linux 中捕获此问题 - 对于 win32 我在 vs2010 中获得堆栈跟踪

css - 如何取消相邻表格单元格的 child ?

java - 在javafx中将节点对齐到Vbox的右侧

c++ - 阵列包装损坏堆

c++ - G++ 无法在某些库中链接,但单独使用 ld 可以找到库

c++ - std::aligned_storage 的 static_cast 和 reinterpret_cast

c++ - 通过 boost 信号 2 的观察者模式