带有 __attribute__ 的 C++ 结构体代码

标签 c++ attributes struct

这段 C++ 代码的作用是什么?怎么会有__attribute__呢?

struct foo { double t[4] __attribute__((aligned(64))); };

最佳答案

来自http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Type-Attributes.html :

aligned (alignment)

This attribute specifies a minimum alignment (in bytes) for variables of the specified type. For example, the declarations:

         struct S { short f[3]; } __attribute__ ((aligned (8)));
         typedef int more_aligned_int __attribute__ ((aligned (8)));

force the compiler to insure (as far as it can) that each variable whose type is struct S or more_aligned_int will be allocated and aligned at least on a 8-byte boundary. On a SPARC, having all variables of type struct S aligned to 8-byte boundaries allows the compiler to use the ldd and std (doubleword load and store) instructions when copying one variable of type struct S to another, thus improving run-time efficiency.

Note that the alignment of any given struct or union type is required by the ISO C standard to be at least a perfect multiple of the lowest common multiple of the alignments of all of the members of the struct or union in question. This means that you can effectively adjust the alignment of a struct or union type by attaching an aligned attribute to any one of the members of such a type, but the notation illustrated in the example above is a more obvious, intuitive, and readable way to request the compiler to adjust the alignment of an entire struct or union type.

因此,该代码实际上要求编译器在 64 字节边界上对齐 t(通常,它会在 8 字节边界上对齐,因为它是一个 )。

关于带有 __attribute__ 的 C++ 结构体代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774689/

相关文章:

c++ - 除了 Boost 的文件系统之外,是否有用于操作文件和目录的良好 C++ 库?

c++ - 如何通过绑定(bind)另一个成员函数的参数来创建 C++ 成员函数?

c++ - 构建 CMake 时使用非默认 libstdc++?

JQuery 解决方案将特定标题从一个项目复制到 div 中的另一个项目

c - csv 文件中的指针和结构

c++ - 使用 g++ 编译 C 代码 : Invalid conversion

attributes - 在OLC模式(openLdap)中添加新的属性类型

python - 从类实例python中删除属性

nhibernate - 将不可变结构映射为 NHibernate 中的组件

来自不兼容指针类型的 C 指针数组赋值