1、定位new运算符是在已分配的内存空间进行二次分配。例如:
char *buffer = new char[512];
Point *p = new (buffer) Point(); //Point为类名
Point *q = new (buffer + sizeof(Point)) Point();
即:在内存缓冲区buffe中创建对象p、q
接下来我们来看一具体例子(参照c++ primer plus):
-------------------------------------------------------------
#include<iostream>
#include<string>
#include<new>
using namespace std;
const int BUF = 512;
class Test
{
private:
string words;
int number;
public:
Test(const string & s = "Test", int n = 0)
{
words =s;
number = n;
cout << words << " constructed\n";
}
~Test()
{
cout << words << " destroyed\n";
}
void Show()
{
cout << words << ", " << number << endl;
}
};
int main()
{
char * buffer = new char [BUF];
Test *p1, *p2;
p1 = new (buffer) Test;
p2 = new Test("heap1", 20);