C ++布局新 [英] C++ placement new

查看:107
本文介绍了C ++布局新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果这个问题听起来很蠢,但我刚开始学习C ++,有一些让我困惑的位置新的

Sorry if this question will sound stupid, but I'm just starting to learn C++ and there is something confusing me about the placement new

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

I've been reading C++ Primer (which I find is a very good book to learn C++), and in the placement new section there is an example given. The example uses a char array to provide memory space for the placement new

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

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

My question is why is it using a char array to provide memory space for the placement new? 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? 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?

再次感谢if

推荐答案


为什么是这样使用字符数组为布局新增了内存空间?

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

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

Why not? char is the smallest type that C++ defines, and on virtually every implementation, it is one byte in size. Therefore, it makes a good type to use when you need to allocate a block of memory of a certain size.

C ++也有非常特殊的机制, c $ c> char (和 char ] ,例如,不会与 char 的对齐方式对齐,它将与任何类型的最大正常对齐方式对齐,你可以使用它来分配内存,然后在该内存中构造任何类型。

C++ also has very specific mechanics about how arrays of char (and only char are allocated. A new char[*], for example, will not be aligned to the alignment of char. It will be aligned to the maximum normal alignment for any type. Thus, you could use it to allocate memory and then construct any type into that memory.


上面代码中的最后一行是为内存分配一个double数组,当原始内存空间包含一个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?

$ b $ b

如果放置new使用的是char数组的内存空间,这是否意味着当我们分配double数组时会覆盖该内存中的char数组?

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 ++布局新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆