内存操作符重载(new/delete)

内存操作符 new 和 delete 系统本身就提供了非常稳固的方法,很少会有情况用到自己重载的 new 和 delete,除非是想实现什么特别的功能,比如在申请内存后自动填入什么数据等等,当然这并不是本文讨论的重点,本文的重点是记录如何重载这两个操作符。

#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

// new delete
void* operator new(size_t size)
{
	void* p = malloc(size);
	// 个性化定制,在申请完内存后将内存数据清0
	memset(p, 0, size);
	cout << "new p = " << p << "\tsize = " << size << endl;
	return p;
}

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

// new delete 组
void* operator new[](size_t size)
{
	void* p = malloc(size);
	memset(p, 0, size);
	cout << "new[] p = " << p << "\tsize = " << size << endl;
	return p;
}

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

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

	friend void* operator new(size_t size);
	friend void operator delete(void* p);
	friend void* operator new[](size_t size);
	friend void operator delete[](void* p);

private:
	int data;
};

int main(int argc, char* argv[])
{
	A *p = new A[5];
	delete [] p;
	return 0;
}

发表评论