newplace.cpp详解
newplace.cpp 是 C++ Primer Plus 第六版中 322 页的示例代码,比较有代表性,可以来讨论讨论运算符 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:" << endl;
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 << "Memory addresses:\n" << " heap:" << pd1
<< " static:" << (void*)buffer