c++ - 调整对齐的 Typedef
问题描述
gcc的“类型属性”页面提供了一个非常有趣的示例,说明如何调整类型别名的对齐方式:
typedef int more_aligned_int __attribute__ ((aligned (8)));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
在这个例子中,more_aligned_int
有不同的对齐方式int
,这在声明这些家伙的数组时变得很明显:
aligned_int ar[3];
输出
error: alignment of array elements is greater than element size
aligned_int ar[3];
^
标准的 C++ 替代方案是alignas
,虽然我很惊讶地发现您实际上可以编写:
using aligned_int = int alignas(8);
编译上述给出:
warning: attribute ignored [-Wattributes]
using aligned_int = int alignas(8);
note: an attribute that appertains to a type-specifier is ignored
所以没有副作用,这就是前面提到的数组声明成功的原因。提问时间:
- 所以
alignas
不等于aligned
属性吗? - 他们有更多不同的方式吗?
- 有没有一种标准的方法来为内置类型创建这样的 typedef(对齐调整)?
解决方案
这些不是一回事。一个是 GCC 扩展,另一个是标准语言功能。
alignas 说明符可以应用于变量或非位域类数据成员的声明,也可以应用于类/结构/联合或枚举的声明或定义。它不能应用于函数参数或 catch 子句的异常参数。
所以标准功能不适用于int
.
扩展确实如此(但随后您会违反数组不存在的后果)。
列举两个不相关的特征之间的所有差异可能没有用。
有没有一种标准的方法来为内置类型创建这样的 typedef(对齐调整)?
您可以将内置类型包装在 a 中struct
:
struct alignas(8) aligned_int
{
int val;
};
aligned_int ar[3];
但请注意,这是可以编译的(可能是因为 的大小aligned_int
已相应更改)。
推荐阅读
- c++ - Premake5 编译额外的可执行文件
- node.js - 发布到 symfony 端点的 Node.js 表单数据为 NULL
- google-cloud-platform - 尽管检查了防火墙规则,但与谷歌云上的虚拟机实例的 HTTP 连接失败
- javascript - 为什么我在使用 Sequelize 填充字段时遇到错误?
- haskell - Haskell 中的“f (a -> b)”类型签名是什么意思?
- opencl - OpenCl:如何使用 INT4/8?
- ruby-on-rails - 如何使 sprockets(或 rack,或 nginx?)激励浏览器缓存字体并正确返回 304?
- docker - 如何从崩溃的 Docker Desktop 容器中获取日志
- node.js - 试图从 mongodb 数据库中检索特定数据,但在控制台中显示未定义
- c++ - 矩阵数据数组的Tensorflow tflite c ++ api推理