Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
781 views
in Technique[技术] by (71.8m points)

C++ placement new

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

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];

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?

Again sorry if the question is strange, but hope I've made it quite clear.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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++ 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.

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?

It is not allocating anything. It is constructing an array, using the memory you have given it. That's what placement new does, it constructs an object in the memory provided.

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?

Yes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...