使用定位new运算符应注意:
- 注意内存覆盖
- delete不能与定位new运算符配合使用,因此要显示地为定位new运算符创建的对象调用析构函数
- 删除顺序:后创建的对象先删除,所有用定位new运算符创建的对象都被删除后再释放用于存储这些对象的缓冲区
#include <iostream>
#include <string>
#include <new>
using namespace std;
const int BUF = 512;
class JustTesting {
private:
string words;
int number;
public:
JustTesting(const string & s = "Just Testing", int n = 0) {
words = s;
number = 0;
cout << words << "constructed\n";
}
JustTesting() { cout << words << "destroyed\n"; }
void show()const { cout << words << "," << number << endl; }
};
int main() {
char * buffer = new char[BUF];
JustTesting *pc1, *pc2;
pc1 = new (buffer) JustTesting;
pc2 = new JustTesting("Heap1", 20);
pc3 = new (buffer + sizeof(JustTesting)) JustTesting("Better idea",4);
pc4 = new JustTesting("Heap2", 10);
delete pc2;
delete pc4;
pc3->~JustTesting();
pc1->~JustTesting();
delete[]buffer;
return 0;
}