// newplace.cpp -- using placement new
#include <iostream>
#include <new> // for placement new
const int BUF = 512;
const int N = 5;
char buffer[BUF]; // chunk of memory
int main() {
using namespace std;
double *pd1, *pd2;
int i;
cout << "Calling new and placement new:\n";
pd1 = new double[N]; // use heap
pd2 = new (buffer) double[N]; // use buffer array
for (i = 0; i < N; i++)
pd2[i] = pd1[i] = 1000 + 20.0 * i;
cout << "Buffer addresses:\n" << " heap: " << pd1 << " static: "
<< (void *) buffer << endl;
cout << "Buffer contents:\n";
for (i = 0; i < N; i++) {
cout << pd1[i] << " at " << &pd1[i] << "; ";
cout << pd2[i] << " at " << &pd2[i] << endl;
}
cout << "\nCalling new and placement new a second time:\n";
double *pd3, *pd4;
pd3 = new double[N];
pd4 = new (buffer) double[N];
for (i = 0; i < N; i++)
pd4[i] = pd3[i] = 1000 + 20.0 * i;
cout << "Buffer contents:\n";
for (i = 0; i < N; i++) {
cout << pd3[i] << " at " << &pd3[i] << "; ";
cout << pd4[i] << " at " << &pd4[i] << endl;
}
cout << "\nCalling new and placement new a third time:\n";
delete[] pd1;
pd1 = new double[N];
pd2 = new (buffer + N * sizeof(double)) double[N];
for (i = 0; i < N; i++)
pd2[i] = pd1[i] = 1000 + 20.0 * i;
cout << "Buffer contents:\n";
for (i = 0; i < N; i++) {
cout << pd1[i] << " at " << &pd1[i] << "; ";
cout << pd2[i] << " at " << &pd2[i] << endl;
}
delete[] pd1;
delete[] pd3;
return 0;
}
Calling new and placement new:
Buffer addresses:
heap: 0x9a35008 static: 0x804a0e0
Buffer contents:
1000 at 0x9a35008; 1000 at 0x804a0e0
1020 at 0x9a35010; 1020 at 0x804a0e8
1040 at 0x9a35018; 1040 at 0x804a0f0
1060 at 0x9a35020; 1060 at 0x804a0f8
1080 at 0x9a35028; 1080 at 0x804a100
Calling new and placement new a second time:
Buffer contents:
1000 at 0x9a35038; 1000 at 0x804a0e0
1020 at 0x9a35040; 1020 at 0x804a0e8
1040 at 0x9a35048; 1040 at 0x804a0f0
1060 at 0x9a35050; 1060 at 0x804a0f8
1080 at 0x9a35058; 1080 at 0x804a100
Calling new and placement new a third time:
Buffer contents:
1000 at 0x9a35008; 1000 at 0x804a108
1020 at 0x9a35010; 1020 at 0x804a110
1040 at 0x9a35018; 1040 at 0x804a118
1060 at 0x9a35020; 1060 at 0x804a120
1080 at 0x9a35028; 1080 at 0x804a128
is static memory, and delete can be used only with a pointer to heap memory allocated by