作用:定位new运算符让我们在动态申请内存时,可以指定要使用的内存位置
使用定位new运算符 :
#include<iostream>
#include<new>
using namespace std;
const int BUF = 512;
const int N = 5;
char buff[BUF];
int main() {
int* pd1, * pd2;
pd1 = new int[N];
pd2 = new (buff)int[N];
for (int i = 0; i < N; i++)
pd1[i] = pd2[i] = 4 * i;
cout << "pd1: " << pd1 << " buff: " << (void*)buff << endl;
cout << endl;
for (int i = 0; i < N; i++){
cout << "pd1[" << i << "]: " << pd1[i] << " at " << &pd1[i] << " ;";
cout << "pd2[" << i << "]: " << pd2[i] << " at " << &pd2[i] << endl;
}
}
运行结果:
分析:
通过定位new运算符将p2放在buff数组中,p2和buff的地址都是00007FF66D9BF440
内存覆盖:
在pd2的基础之上,通过定位new运算符将数组pd3放在buff中,pd4会覆盖在原来pd1的内存位置
int* pd3, * pd4;
pd3 = new int[N];
pd4 = new (buff)int[N];
for (int i = 0; i < N; i++)
pd3[i] = pd4[i] = 5 * i;
cout << endl;
for (int i = 0; i < N; i++) {
cout << "pd3[" << i << "]: " << pd3[i] << " at " << &pd3[i] << " ;";
cout << "pd4[" << i << "]: " << pd4[i] << " at " << &pd4[i] << endl;
}
运行结果:
这里pd4和pd2的地址相同,pd4的值覆盖了pd2的值,为了能继续buff中创建数组,且不覆盖之前的值,需要计算一个偏移量
pd2 = new (buff + N * sizeof(int))int[N];
for (int i = 0; i < N; i++)
pd2[i] = 6 * i;
cout << endl;
for (int i = 0; i < N; i++) {
cout << "pd2[" << i << "]: " << pd2[i] << " at " << &pd2[i] << endl;
}
运行结果: