C++ 安置新

标签 c++

如果这个问题听起来很愚蠢,我很抱歉,但我才刚刚开始学习 C++,我对 new 的位置有些困惑

我一直在阅读 C++ Primer(我发现这是一本非常好的学习 C++ 的书),并且在 placement new 部分中给出了一个示例。示例使用char数组为放置new提供内存空间

const int BUF = 512;
const int N = 5;
char buffer[BUF];
double * pd1;
pd1 = new (buffer) double[N];

我的问题是为什么要用char数组为placement new提供内存空间?还有上面代码的最后一行是为一个double数组分配内存,当原来的内存空间是一个char数组怎么可能呢?如果 placement new 使用的是 char 数组的内存空间,这是否意味着当我们分配 double 数组时它会覆盖该内存中的 char 数组?

再次抱歉,如果问题很奇怪,但希望我已经说得很清楚了。

最佳答案

why is it using a char array to provide memory space for the placement new?

为什么不呢? char 是 C++ 定义的最小类型,几乎在每个实现中,它的大小都是一个字节。因此,当您需要分配一定大小的内存块时,它是一个很好的类型。

C++ 对于如何分配char(和 char)数组也有非常具体的机制。A new char[* ],例如,不会与 char 的对齐方式对齐。它将与任何类型的最大正常对齐方式对齐。因此,您可以使用它来分配内存,然后将任何类型构造到该内存中。

Also the last line in the code above is allocating memory for an array of double, how is that possible when the original memory space contains a char array?

它没有分配任何东西。它正在构造一个数组,使用你给它的内存。这就是 placement new 所做的,它在提供的内存中构造一个对象。

If the placement new is using the memory space of the char array, does this mean when we allocate the double array it overwrites the char array in that memory?

是的。

关于C++ 安置新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31115850/

相关文章:

c++ - 在 Windows 操作系统上使用 C++ 开发 iPad/iPhone 应用程序

c++ - 尝试堆插入时访问冲突写入位置

Python - OpenCV 模块缺少属性 CV_CALIB_FIX_INTRINSIC

c++ - OpenGL 顶点缓冲区渲染不正确

c++ - 从 MinGW 程序调用 Postgres 的最简单方法是什么?

c++ - 如何只选择需要的 Qt 头文件?

c++ - 按住鼠标左键时未生成 WM_MOUSELEAVE

c++ - const 对象的代码大小

c++ - unordered_map vs vector + 少量元素的自定义散列

c++ - 堆损坏,可能的内存泄漏,C++