【C++内存管理】placement new 重载示例

本文介绍了C++中placement new的概念,展示了如何为operator new和operator delete编写重载版本,特别是在处理构造函数抛出异常时的情况。通过示例代码解释了在异常发生时,如何确保内存的正确管理。尽管在VS2017中未观察到预期的行为,但重载的operator delete仍然用于异常情况下的内存回收。
摘要由CSDN通过智能技术生成

可以为 operator new 写出多个重载版本,但是每一个版本的第一个参数都必须为 size_t 类型。其余的参数以 new 所指定的 placement arguements 为初值,出现在 new(…) 小括号里面的就是所谓的 placement arguements.
比如我们可以继续为 Foo 类型写 operator new 重载:

class Foo
{
   
public:
	Foo() : _id(0)
	{
   
		cout << "default constructor. id = " << _id << endl;
	}
	Foo(int i) : _id(i)
	{
   
		cout << "constructor. id = " << _id << endl;
	}
	~Foo()
	{
   
		cout << "destructor. id = " << _id << endl;
	}

	//一般的 operator new 重载
	void* operator new(size_t size)
	{
   
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值