17~C++ new和delete运算符重载

戏子无情 提交于 2020-01-03 14:02:26

重载 class A的new/delete 以及 new[]/delete[]运算符:
成功返回非空指针,失败返回空指针

#include <iostream>
#include <cstdlib>
using namespace std;
class A {
public:
	A (int var = 0) : m_var (var) {
		cout << "A构造:" << this << endl;
	
	}
	~A (void) {
		cout << "A析构:" << this << endl;
	}
	static void* operator new (size_t size) {
		void* pv = malloc (size);
		cout << "new:" << size << ' ' << pv
			<< endl;
		return pv;
	}
	static void operator delete (void* pv) {
		cout << "delete:" << pv << endl;
		free (pv);
	}
	static void* operator new[] (size_t size){
		void* pv = malloc (size);
		cout << "new[]:" << size << ' ' << pv
			<< endl;
		return pv;
	}
	static void operator delete[] (void* pv) {
		cout << "delete[]:" << pv << endl;
		free (pv);
	}
private:
	int m_var;
	string m_str;
};
int main (void) {
	A* pa = new A (100);
//	A* pa = (A*)A::operator new (sizeof (A));
//	A::A (pa, 100);
	cout << "pa = " << pa << endl;
	delete pa;
//	A::~A (pa);
//	A::operator delete (pa);
	pa = new A[5] {200, 300, 400, 500, 600};
	cout << "pa = " << pa << endl;
	cout << *((int*)pa-1) << endl;
	delete[] pa;
//	delete pa;
//	cout << 2 > 1 << endl;
	cout << (2 > 1) << endl;
	return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!