码迷,mamicode.com
首页 > 其他好文 > 详细

自定义new和delete

时间:2015-03-14 21:31:24      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

#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;
}

 

自定义new和delete

标签:

原文地址:http://www.cnblogs.com/chunyou128/p/4338225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!