#include <iostream>
#include <new>
using namespace std;
int main()
{
//operator new申请一块内存空间,用来存储string对象
void *rawMemory = operator new(sizeof(string));
//用string指针指向此块内存空间,使这块内存被视为一个string对象
string *ps = static_cast<string *>(rawMemory);
//使用placement new构造此块内存中的对象
new (ps) string ();
cout << ps->length() << endl;
ps->append("abcdefg"); //追加内容
cout << ps->length() << endl;
ps->~string(); //析构
cout << ps->length() << endl;
operator delete(ps); //释放空间
return 0;
}
operator new申请的空间为未初始化的void *空间,对于operator new申请的内存,不可以直接用delete来释放(此操作包含析构和释放两步操作),只可以用operator delete来释放相应的区域。在此处初始化使用的是placement new操作符,使用析构函数对此处区域进行析构之后可释放内存区域。