GCC中的结构对齐(应该在typedef中指定对齐吗?)
Structure alignment in GCC (should alignment be specified in typedef?)
对不起,这是一个愚蠢的问题,但如果我需要确保结构/类/联合的对齐,我应该添加属性((aligned(align)))到typedef声明吗?
class myAlignedStruct{} __attribute__ ((aligned(16)));
typedef myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?
我应该添加属性((aligned(align)))到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
公认的答案("否")是正确的,但我想澄清其中一个可能令人误解的部分。我会添加注释,但需要格式化一些代码;因此有了新的答案。
类型定义只是指定的实际类型的假名或别名,它们不作为单独的类型存在以具有不同的对齐方式,包装等。
这是不正确的,至少对于GCC (OP的编译器)和li。例如,下面的编译没有错误,表明可以将对齐附加到typedef。
反常对齐(大于对象的大小)仅仅是为了震慑和娱乐价值。
#define CASSERT( expr ) { typedef char cassert_type[(expr) ? 1 : -1]; }
typedef __attribute__((aligned(64))) uint8_t aligned_uint8_t;
typedef struct
{
aligned_uint8_t t;
} contains_aligned_char_t;
void check_aligned_char_semantics()
{
CASSERT(__alignof(aligned_uint8_t) == 64);
CASSERT(sizeof(aligned_uint8_t) == 1);
CASSERT(sizeof(contains_aligned_char_t) == 64);
}
相关文章:
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 如何创建一个QTableWidgetItem,用长文本右对齐,左边有省略号
- 我可以检测和更改 gcc/g++ 中结构的当前数据对齐设置吗?
- 64位机器上的C++内存对齐
- 为什么我可以将变量存储在不是其最小对齐方式的倍数的地址?
- 使 std::vector 分配对齐内存的现代方法
- C++ cout 将双精度对齐到精度 2 并正确对齐
- 在 64 位边界上对齐C++结构数组?
- 使用 g++7 构建的代码在访问未对齐的内存时崩溃
- 在 capnp FlatArrayMessageReader 的对齐内存缓冲区中接收 zmq 消息
- 是否值得对齐变量?
- 初始化派生结构的基部分/意外打包派生结构字段以对齐基结构的间隙
- 对齐和对齐的实际用例C++关键字
- 如何减少代码的运行时间以对齐文本?
- 指向包含对齐 C 结构C++类的 C 指针的对齐问题
- Linux C++ 中的页面对齐内存分配
- C++ 类层次结构中的"对齐"是什么意思?
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 具有调整对齐方式的类型定义
- GCC中的结构对齐(应该在typedef中指定对齐吗?)