如何使用alignof强制对齐的堆分配? [英] How use alignof to force alignment for a heap allocation?

查看:123
本文介绍了如何使用alignof强制对齐的堆分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想强制特定的堆分配返回一个64字节对齐的地址,因为这是一个缓存行边界。我想我可以这样做

I'd like to force a specific heap allocation to return an address that's 64-byte aligned, because that's a cache line boundary. I thought I could do it like this

int *p = new alignas(64) int;

但我的编译器都没有给出 p 一个地址是64的倍数。这是我如何检查:

but none of my compilers seem to give p an address that's a multiple of 64. Here's how I'm checking:

#include <iostream>

int main()
{
  int *p = new alignas(64) int;
  std::cout << long(p) % 64 << '\n';    // should print 0
}

我必须做错事。但是什么?

I must be doing something wrong. But what?

推荐答案

new 分配空间是假设返回指针到存储器,该存储器对于具有基本
对齐的任何类型的对象适当地对齐(§ 3.7.4.1/2; quote是来自< 5.3.4 / 11)。 alignas(64)可能不是您的编译器和环境的基本对齐方式,因此分配函数不需要遵守它。

The allocator called by the new operator in order to allocate space is "assumed to return pointers to storage that is appropriately aligned for objects of any type with fundamental alignment" (§3.7.4.1/2; quote is from §5.3.4/11). alignas(64) is probably not a "fundamental alignment" for your compiler and environment, so the allocation function doesn't need to respect it.

请注意,分配函数只传递请求的空间量;它不知道正在请求对齐。

Note that the allocation function is only passed the amount of space requested; it has no idea what alignment is being requested. Consequently, it cannot adjust its result to fit special needs.

alignas 类型说明符设计用于使用静态和自动对象。对于这样的对象,如果它是基本的,则必须遵守请求的对齐,并且在理想世界中,如果编译器不能保证将遵守扩展对齐,则编译器将产生错误消息。 (我不相信它有义务这样做,虽然; gcc和clang产生可执行文件segfault如果请求一个巨大的栈对齐。)

The alignas type specifier is designed to work with static and automatic objects. With such objects, the requested alignment must be respected if it is fundamental, and in an ideal world the compiler would produce an error message if it cannot guarantee that an extended alignment would be respected. (I don't believe it's obliged to do so, though; both gcc and clang produce executables which segfault if a huge stack-alignment is requested.)

这篇关于如何使用alignof强制对齐的堆分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆