#include <iostream>
#include <string>
#include <new> // 引用布局new
const int BUF = 512;
using namespace std;
/* 主要演示在布局new如何存放对象与释放对象
* 因为变量都是对象指针,本来都需要人工释放对象
* 但使用布局NEW 会有所不同
*/
class TestClass{
private:
string words;
public:
TestClass(char * str = "default string"){
words = str;
}
~TestClass(){}
void show() const{
cout << words << endl;
}
};
int main()
{
char * buffer = new char[BUF];
TestClass *tc1, *tc2;
// 使用布局new 把对象放在数组里,不申请堆内存
tc1 = new (buffer) TestClass("Buffer");
tc2 = new TestClass("Heap"); // 申请堆内存,把对象放在堆里
cout << "buffer addr:= " << (void *)buffer << endl;
cout << "tc1 addr:= " << tc1 << " data:= ";
tc1->show();
cout << "tc2 addr:= " << tc2 << " data:= ";
tc2->show();
tc1->~TestClass();// 需要手工调用析构函数,
delete tc2; // 释放对象 tc2
delete [] buffer; // 释放缓存;
return 0;
}
#include <string>
#include <new> // 引用布局new
const int BUF = 512;
using namespace std;
/* 主要演示在布局new如何存放对象与释放对象
* 因为变量都是对象指针,本来都需要人工释放对象
* 但使用布局NEW 会有所不同
*/
class TestClass{
private:
string words;
public:
TestClass(char * str = "default string"){
words = str;
}
~TestClass(){}
void show() const{
cout << words << endl;
}
};
int main()
{
char * buffer = new char[BUF];
TestClass *tc1, *tc2;
// 使用布局new 把对象放在数组里,不申请堆内存
tc1 = new (buffer) TestClass("Buffer");
tc2 = new TestClass("Heap"); // 申请堆内存,把对象放在堆里
cout << "buffer addr:= " << (void *)buffer << endl;
cout << "tc1 addr:= " << tc1 << " data:= ";
tc1->show();
cout << "tc2 addr:= " << tc2 << " data:= ";
tc2->show();
tc1->~TestClass();// 需要手工调用析构函数,
delete tc2; // 释放对象 tc2
delete [] buffer; // 释放缓存;
return 0;
}