问题描述
我的问题很简单;
alignas指定符是否与"new"一起使用?也就是说,如果将一个结构定义为对齐的,那么分配给new的结构会对齐吗?
Does the alignas specifier work with 'new'? That is, if a struct is defined to be aligned, will it be aligned when allocated with new?
推荐答案
如果类型的对齐方式未过度对齐,则可以,默认的new
将起作用. 过度对齐"表示您在alignas
中指定的对齐方式大于alignof(std::max_align_t)
.默认的new
会偶然地或多或少地与非过度对齐类型一起使用;默认的内存分配器将始终以小于等于alignof(std::max_align_t)
的对齐方式分配内存.
If your type's alignment is not over-aligned, then yes, the default new
will work. "Over-aligned" means that the alignment you specify in alignas
is greater than alignof(std::max_align_t)
. The default new
will work with non-over-aligned types more or less by accident; the default memory allocator will always allocate memory with an alignment equal to alignof(std::max_align_t)
.
但是,如果您的类型的对齐方式过度对齐,则表示您不走运.默认的new
或您编写的任何全局new
运算符都无法知道该类型所需的对齐方式,更不用说为其分配适当的内存了.解决这种情况的唯一方法是重载类的operator new
,它将能够使用alignof
查询类的对齐方式.
If your type's alignment is over-aligned however, your out of luck. Neither the default new
, nor any global new
operator you write, will be able to even know the alignment required of the type, let alone allocate memory appropriate to it. The only way to help this case is to overload the class's operator new
, which will be able to query the class's alignment with alignof
.
当然,如果该类用作另一个类的成员,则这将不会有用.除非该其他类也重载operator new
,否则不会.因此,像new pair<over_aligned, int>()
这样简单的内容将无法正常工作.
Of course, this won't be useful if that class is used as the member of another class. Not unless that other class also overloads operator new
. So something as simple as new pair<over_aligned, int>()
won't work.
针对C ++ 17的提案(已被接受)添加了通过超载operator new/delete
并采用要分配类型的alignof
来支持动态分配超对齐类型.这还将支持小于最大对齐类型的对齐方式,因此您的内存分配器不必总是返回与alignof(std::max_align_t)
对齐的内存.
A proposal for C++17 (which has been accepted) adds support for dynamic allocation of over-aligned types, by having overloads of operator new/delete
that take the alignof
of the type being allocated. This will also support alignments of less than the max aligned type, so your memory allocator need not always return memory aligned to alignof(std::max_align_t)
.
话虽这么说,不需要编译器完全支持过度对齐的类型.
That being said, compilers are not required to support over-aligned types at all.
这篇关于alignas说明符是否与"new"一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!