Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 具有对齐存储的动态内存分配_C++_C++11 - Fatal编程技术网

C++ 具有对齐存储的动态内存分配

C++ 具有对齐存储的动态内存分配,c++,c++11,C++,C++11,当使用std::aligned_storage并且需要动态分配时,我对对齐要求有点困惑。例如: using storage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type; storage* pool; pool = ::new storage[num_obj]; 使用storage=typename std::aligned_storage::typ

当使用
std::aligned_storage
并且需要动态分配时,我对对齐要求有点困惑。例如:

  using storage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
  storage* pool;
  pool = ::new storage[num_obj];
使用storage=typename std::aligned_storage::type;
存储*池;
池=::新存储[num_obj];

这合法吗?新操作符不返回对齐内存,因此结果正确吗?

C++11标准要求分配函数,如
::操作符新
返回对齐的内存(std::max_align_t):

返回的指针应适当对齐,以便能够转换为具有基本对齐要求的任何完整对象类型的指针[…]

因此,只要通过
new
表达式创建的对象类型不是过度对齐的类型(需要比
alignof(std::max\u align\u t)
更严格的对齐),一切都可以。对于过度对齐的类型,您确实需要分配足够大小的存储来手动对齐指针,例如,使用,然后在适当的地址构造对象,例如,通过放置新的

从C++17开始,
new
会自动处理这个问题。若要分配需要比
\uu STDCPP\uudefault\uuunew\uuualignment\uuuuuuuuu更严格的对齐方式的存储(分配函数至少需要提供的对齐方式),新表达式将调用一个分配函数,该函数将显式地给出要分配的存储的对齐方式作为参数