自定义new和delete

时间:2021-12-19 19:43:36
#include "stdafx.h"
#include <stdlib.h>
#include <malloc.h>

#include <iostream>
#include<windows.h>
using namespace std;

class Myclass;
Myclass* x1 = NULL;
Myclass* x2 = NULL;
Myclass* x3 = NULL;
class Myclass
{
public:
	Myclass();
	~Myclass();
public:
	void* operator new(size_t);
	void operator delete(void*);
public:
	static int m_num;
};

int Myclass::m_num = 0;
Myclass::Myclass()
{

}

Myclass::~Myclass()
{
}

void* Myclass::operator new(size_t size)
{
	++Myclass::m_num;
	if (m_num >= 3)
	{
		MessageBox(0,L"You could only new three times",L"new",0);
	}

	void *storage = malloc(size);
	if(NULL == storage) {
		throw "allocation fail : no free memory";
	}
	return storage;
}

void Myclass::operator delete(void* pointee)
{
	cout<<"operator delete"<<endl;
	::operator delete(pointee);
}

int _tmain(int argc, _TCHAR* argv[])
{
	x1 = new Myclass;
	delete(x1);
	x2 = new Myclass;
	delete(x2);
	x3 = new Myclass;
	delete(x3);

	system("pause");
	return 0;
}