在指定的内存地址创建对象

时间:2022-08-30 18:04:53
// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "ioStream.h"
#include <new>

//类
class Test
{
public://构造方法
Test()
{
cout << "创建" << endl;
}
~Test()//释构方法
{
cout << "释放" << endl;
}
char *getName()//成员方法
{
return "Test";
}
};

int main(int argc, char* argv[])
{
//创建内存缓冲区,也可以是页面内存
char * buff = new char [sizeof (Test) ];
Test * pTest = new (buff) Test;//在指定的内存地址创建对象

//cout << ((Test*)buff)->getName() << endl;//调用对象
cout << pTest->getName() << endl;//调用对象

pTest->~Test();//释放对象
delete []buff;//删除缓冲区
return 0;
}