Reputation: 353
I am reading a document given to me by a professor and I'm trying to understand the following line of code.
C *r = new(p) C[3];
what exactly is the code doing? What does the C[3] after the new(p) accomplish?
Upvotes: 1
Views: 34
Reputation: 111279
This line of code constructs an array of 3 items of type C
, similar to this, which is hopefully more familiar to you:
C *r = new C[3];
The primary difference is that new(p)
does not allocate new memory; instead it constructs the array in a pre-existing memory buffer pointed by p
. For example:
char *p = new char[3*sizeof(C)];
C *r = new(p) C[3];
Another difference is that you can't use delete[]
to call the deconstructors and free the memory. You have to call the deconstructors manually
for (int i=0; i<3: i++) r->~C();
delete[] p;
See also What uses are there for "placement new"? and Wikipedia.
Upvotes: 1