c++ - 由非扩展分配函数创建的 char 数组

标签 c++

N3797 第 5.3.4/10 节说:

When a new-expression calls an allocation function and that allocation has not been extended

[...]

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.

我不明白这个限制。

考虑分配给 char *p 的以下新表达式结果:

char *p = new char[5];

让在计算新表达式分配函数期间返回指向地址 a1 的指针。确定最严格基本对齐的算法是什么 a T 型 sizeof(T)<=5 ?实现如何确定地址是否为a1+a存在吗?

最佳答案

当您执行数组new时,传递给分配函数的大小是您正在分配的数组的大小加上未指定的数组分配开销。分配函数需要返回一个指向具有基本对齐的任何类型的地址的指针:

  ---------------------------------------
  |  overhead  | actual array           |
  ---------------------------------------
  ^            ^
  |            |
  |            What the array new expression returns
  | 
  What the allocation function returns
  (correctly aligned for any object type with fundamental alignment)

因此,“new-表达式的结果与分配函数返回的地址之间的差异”就是数组分配开销的大小。

基本对齐是小于或等于 alignof(std::max_align_t) (§3.11 [basic.align]/p2) 的对齐,并且对齐必须是 2 的幂 (p4)。因此,很容易确定“T类型的最严格基本对齐a,其中sizeof(T)”不大于任何给定的数字。可能的基本对齐方式只有这么多。

您引用的要求要求数组 new 表达式的返回值对于具有可容纳在缓冲区内的基本对齐方式的任何类型进行正确对齐。通过将数组分配开销的大小调整为该对齐要求的倍数,实现可以轻松地做到这一点。它可以通过将开销大小设置为alignof(std::max_align_t)的倍数来轻松实现此目的,以便数组new返回的指针始终与任何类型对齐基本对齐。

关于c++ - 由非扩展分配函数创建的 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25002044/

相关文章:

c++ - 没有用于调用连接的匹配函数 - Qt 5.5

C++ 通过引用传递 : two level deep function calls

c++ - 如何多次正确引用此指针?

C++ 独立函数文件

c++ - 为什么 unordered_map 的 emplace with piecewise_construct 参数需要默认构造函数?

c++ - 将字符串解析为int

c++ - Qt在linux上打印坐标错误

c++ - C++ 中的 ifstream 对象数组

C++ 和 Objective-C

C++ 使用 std::move 将映射复制到 vector