gpt4 book ai didi

c++ - 我可以使用 std::align 将内存对齐到任意值 2 吗?

转载 作者:太空狗 更新时间:2023-10-29 21:32:49 26 4
gpt4 key购买 nike

我很难解释来自 https://en.cppreference.com/w/cpp/memory/alignstd::align 的以下描述

void* std::align(std::size_t alignment,
std::size_t size,
void*& ptr,
std::size_t& space );

The behavior is undefined if alignment is not a fundamental or extended alignment value supported by the implementation (until C++17) power of two (since C++17).

如果我的理解是正确的,那么这意味着对于 C++11 使用 std::align 是未定义的行为,如果您请求的对齐方式与 C++ 内置类型之一的对齐方式不匹配,例如 short, int, long, double, ....因此,使用对齐值大于 std::max_align_t(通常为 8 或 16)的 std::align 会导致未定义的行为。

但现在对于 C++17 有一个变化:

... power of two (since C++17).

我想这意味着自 C++17 以来,任何 2 的幂值都是 std::align 的有效对齐方式。

谁能证实这一点?

更新:

对于 GCC 和 LLVM 的 std::align 实现,任何 2 的幂值都是有效对齐。对于任何非 2 的幂对齐值,GCC 和 LLVM 的 std::align 实现会导致未定义的行为。

这似乎证实了我的假设:

since C++17 any power of 2 value is a valid alignment for std::align.

而且我已经测试过,即使对于 C++11,std::align 也可以使用 GCC、LLVM 和 MSVC 对任何 2 的幂对齐值正确工作。

最佳答案

for C++11 using std::align is undefined behavior if your requested alignment does not match the alignment of one of the C++ builtin types like short, int, long, double, ....

那不是 cppreference 或 the standard 的意思说。来自 C++14 [ptr.align]/2.1:

alignment shall be a fundamental alignment value or an extended alignment value supported by the implementation in this context

基本对齐不是基本类型的对齐。来自 [basic.align]/2 :

A fundamental alignment is represented by an alignment less than or equal to the greatest alignment supported by the implementation in all contexts, which is equal to alignof(std::max_align_t) (18.2).

原来如此。结合 [basic.align]/4 的所有对齐必须是二次幂的声明,这意味着基本对齐是小于或等于 alignof(std::max_align_t) 的任何对齐。

关于c++ - 我可以使用 std::align 将内存对齐到任意值 2 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682190/

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