gpt4 book ai didi

c++ - gcc 过度对齐的新支持 (alignas)

转载 作者:可可西里 更新时间:2023-11-01 16:38:35 28 4
gpt4 key购买 nike

我很难找到有关 GCC 的 aligned-new 警告和 gcc -faligned-new 选项的更多信息。在 gcc 7.2.0 上编译(没有 --std=c++17)并尝试定义一个对齐的结构,例如:

struct alignas(64) Foo { int x; }

只是做一个普通的旧:

Foo * f = new Foo();

给我以下警告和建议:

 alignas.cpp:36:25: warning: ‘new’ of type ‘Foo’ with extended alignment 64 [-Waligned-new=]
Foo * f = new Foo();
^
alignas.cpp:36:25: note: uses ‘void* operator new(long unsigned int)’, which does not have an alignment parameter
alignas.cpp:36:25: note: use ‘-faligned-new’ to enable C++17 over-aligned new support

我知道默认情况下 new 只会返回与 alignof( std::max_align_t ) 对齐的内存(对我来说是 16),但不清楚的是我的问题是,如果我通过 -faligned-new,gcc 现在会代表我执行 new 的正确新对齐吗?

不幸的是,关于这个的 gcc 文档非常缺乏。

最佳答案

来自 gcc's manual :

-faligned-new
Enable support for C++17 new of types that require more alignment than void* ::operator new(std::size_t) provides. A numeric argument such as -faligned-new=32 can be used to specify how much alignment (in bytes) is provided by that function, but few users will need to override the default of alignof(std::max_align_t).

这意味着 -faligned-new 只是让 aligned-new 功能添加到 P0035R4 中无需完全启用 C++17 支持即可使用。

C++标准中的相关位:
来自 [cpp.predefined]:

__STDCPP_DEFAULT_NEW_ALIGNMENT__
An integer literal of type std::size_t whose value is the alignment guaranteed by a call to operator new(std::size_t) or operator new[](std::size_t). [ Note: Larger alignments will be passed to operator new(std::size_t, std::align_val_t), etc. (8.3.4). — end note ]

来自 [basic.align/3]:

A new-extended alignment is represented by an alignment greater than __STDCPP_DEFAULT_NEW_ALIGNMENT__

来自 [expr.new/14]:

Overload resolution is performed on a function call created by assembling an argument list. The first argument is the amount of space requested, and has type std::size_t. If the type of the allocated object has new-extended alignment, the next argument is the type’s alignment, and has type std::align_val_t.


所以在你使用 C++17 或 -faligned-new 的情况下,因为 Foonew-extended alignmentFoo* f = new Foo( ); 将调用 void* operator new(size_t, align_val_t) 来分配内存并返回指向在 64- 上正确对齐的 Foo 对象的指针字节边界。根据早期标准,情况并非如此。

关于c++ - gcc 过度对齐的新支持 (alignas),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49373287/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com