C ++ 11中的动态对齐内存分配 [英] Dynamic aligned memory allocation in C++11

查看:297
本文介绍了C ++ 11中的动态对齐内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

posix_memalign和_aligned_malloc在Windows上允许动态分配对齐的内存块。在C ++ 11中有类似的东西吗?据我所知,alignas关键字只适用于静态分配的对象。非常感谢。

解决方案

这取决于所需的对齐方式。对于任何<=到 alignof(std :: max_align_t) new 按照n3242工作3.7.4.1/2 :


返回的指针应适当对齐,以便它可以
转换为任何完整对象类型的指针基本
对齐要求


std :: max_align_t c> $ 的数组的分配。



< unsigned char
但不是 signed char 在5.3.4 / 10中有不同的规则:



< blockquote>

对于char和unsigned char数组,new-expression的结果
和分配
函数返回的地址之间的差异应该是















b $ b

所以 new char [1]; 可以对齐为1.



分配大于 alignof(std :: max_align_t)的对齐内存,C ++ 11不提供直接的方法来做到这一点。唯一可靠的方法是至少分配 size + alignment 字节,并使用 std :: align 以在此缓冲区中获得正确对齐的位置。



这可能会浪费大量内存,因此如果您需要很多这些,你可以创建一个分配器,分配一个大到足够大的块,并使用std :: align。



您的其他选项是等待 http://open-std.org/JTC1/SC22/WG21/docs/papers/2012/n3396.htm ,使其成为标准。



我个人只是在操作系统提供的API上编写一个抽象层来分配对齐的内存。


posix_memalign and _aligned_malloc on Windows allow to dynamically allocate an aligned chunk of memory. Is there anything similar in C++11? As far as I know, the alignas keyword only works with statically allocated objects. Thanks a lot in advance.

解决方案

It depends on what alignment you require. For anything <= to alignof(std::max_align_t), new works as per n3242 3.7.4.1/2:

The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement

std::max_align_t is a complete object type with the strictest fundamental alignment.

Note that allocation of arrays of char or unsigned char but not signed char have a different rule in 5.3.4/10:

For arrays of char and unsigned char, the difference between the result of the new-expression and the address returned by the allocation function shall be an integral multiple of the strictest fundamental alignment requirement (3.11) of any object type whose size is no greater than the size of the array being created.

So new char[1]; can have an alignment of 1.

As for allocating memory with an alignment greater than alignof(std::max_align_t), C++11 provides no direct way to do this. The only reliable way is to allocate at least size + alignment bytes and use std::align to get a correctly aligned location in this buffer.

This can waste a lot of memory, so if you need a lot of these, you could create an allocator that allocates a chunk large enough for all of them and use std::align on that. Your overhead is then amortized across all of the allocations.

Your other option is to wait for http://open-std.org/JTC1/SC22/WG21/docs/papers/2012/n3396.htm to make it into the standard.

Personally I would just write an abstraction layer over the OS provided APIs for allocating aligned memory.

这篇关于C ++ 11中的动态对齐内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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