new与delete的重载

new与delete的重载

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <string.h>


//new 和delete的重载
//new new[] delete delete[]
//适用于极个别情况需要定制的时候才用的到。一般很少用


//声明可以不加 参数
//void *operator new(size_t);
//void operator delete(void *);
//void *operator new[](size_t);
//void operator delete[](void *);


class A
{
public:
	A()
	{
		cout << "A()" << endl;
	}
	~A()
	{
		cout << "~A()" << endl;
	}

	void func()
	{
		cout << "i am a function" << endl;
	}

	//size_t 为 unsigned int
	void *operator new(size_t size) //重载之后取代全局
	{
		cout << "size= " << size << endl;
		cout << "void *operator new(size_t)" << endl;
		void* p = malloc(size);
		memset(p, 0, size);

		((A*)p)->data = 100; //代表可以在实现定制化的函数内初始化
		//可以实现自我早期的定制 早于构造器初始化

		return p;
	}

	void operator delete(void *p)  //重载之后取代全局
	{
		cout << "void operator delete(void *)" << endl;
		free(p);
	}


	void *operator new[](size_t size)
	{
		cout << "size= " << size << endl; //没懂打印出为啥是24
		cout << "void *operator new[](size_t size)" << endl;
		void* p = (void*)malloc(size);
		return p;
	}


	void operator delete[](void * p)
	{
		cout << "void operator delete[](void *)" << endl;
		free(p);
	}

	int data;
};




//定制化,我要实现A类对象的生成,用我自己定制的new delete
//而其他仍用系统的 就把要实现的函数作为类A的成员函数

int _tmain(int argc, _TCHAR* argv[])
{
	A* pa = new A; //new 会调用构造器

	pa->func();

	cout << pa->data << endl;

	delete pa; //delete 会调用析构器

	//A* pm=(A*)malloc(sizeof(A)); //malloc不会调用构造器
	//free(pm); //free不会调用析构器

	cout << "==============================" << endl;

	A* pb = new A[5];

	delete[]pb;

	cout << "===========================" << endl;

	int *p = new int; //系统的

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值