C++Primer Plus第12章类和动态内存分配--再谈定位new运算符----12.9

该程序使用定位 new运算符在相邻的内存单元中创建两个对象,并调用了合适的析构函数。

#pragma region 12.9 placenew2.cpp
//placenew2.cpp -- new placement new,no  delete

#if 1
#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 = n; 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);

	cout << endl << "memory block address:\n" << "buffer: "
		<< (void*)buffer << "  heap: " << pc2 << endl << endl;

	cout << "Memory contents:\n";
	cout << pc1 << ": ";
	pc1->Show();
	cout << pc2 << ": ";
	pc2->Show();

	cout << endl;
	JustTesting* pc3, * pc4;
	//控制偏移
	pc3 = new(buffer + sizeof(JustTesting))JustTesting("Bad Idea", 6);
	pc4 = new JustTesting("Heap2", 10);

	cout << endl << "Memory contents:\n";
	cout << pc3 << ": ";
	pc3->Show();
	cout << pc4 << ": ";
	pc4->Show();

	delete pc2; //free heap1,heap2;
	delete pc4;
	//释放顺序和申请顺序相反
	pc3->~JustTesting();
	pc1->~JustTesting();
	delete[]buffer;	//free buffer;
	cout << "Done\n";
	return 0;
}
#endif
#pragma endregion

在这里插入图片描述
总结:
1,从从而是看,在buffer中申请的地址是不一样的。
2,四个对象的析构函数都得到了释放
3,delete的顺序和new的顺序相反,最后new的最先delete

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值