走进C++程序世界-----operator new delete 重载

 在C++ 的世界里,new 和delete 是keyword,而在C的世界里相相应的malloc和free是函数,关键C++的new和delete分析,详见前面的章节。这里就不在过多的介绍了。链接

以下来研究下关于new 和delete的重载。

 1、对照使用重载和未使用重载

 未使用“

/*File : operator_new.cpp
 *Auth : sjin
 *Date : 2014-04-27
 *Mail : 413977243@qq.com
 */

#include <iostream>

using namespace std;

class test {
public:
	test(){cout << "*****构造test()*****"<< endl;};
	~test(){cout << "+++++析构test()+++++"<< endl;};
};

int main()
{
	test * x = new test;//运行分配空间。再运行析构函数
	delete x;//先运行析构函数,在释放空间
}

使用重载后,

/*File : operator_new.cpp
 *Auth : sjin
 *Date : 2014-04-27
 *Mail : 413977243@qq.com
 */

#include <iostream>

using namespace std;

char mem[10000] = {'\0'};
int pos = 0;

class test {
public:
	test(){cout << "*****构造test()*****"<< endl;};
	~test(){cout << "+++++析构test()+++++"<< endl;};

public:
	void * operator new(size_t bytes){
		cout << "------new test()------" << endl;
		int alloc = pos;
		pos += bytes;
		return (mem + alloc);
	};

	void operator delete(void *){
		cout << "------delete test()------" << endl;

	};
};

int main()
{
	test * x = new test;

	delete x;
}


/*File : operator_new.cpp
 *Auth : sjin
 *Date : 2014-04-27
 *Mail : 413977243@qq.com
 */

#include <iostream>

using namespace std;

char mem[10000] = {'\0'};
int pos = 0;

class test {
public:
	test(){cout << "*****构造test()*****"<< endl;};
	~test(){cout << "+++++析构test()+++++"<< endl;};

public:
	void * operator new(size_t bytes){
		cout << "------new test()------" << endl;
		int alloc = pos;
		pos += bytes;
		return (mem + alloc);
	};

	void operator delete(void *){
		cout << "------delete test()------" << endl;

	};
};

int main()
{
	test * x = new test;

	delete x;

	x = new test[3];

	delete [] x;//这里对数组释放,须要注意
}


#include <iostream>

using namespace std;

char mem[10000] = {'\0'};
int pos = 0;

class test {
public:
	test(){cout << "*****构造test()*****"<< endl;};
	~test(){cout << "+++++析构test()+++++"<< endl;};

public:
	void * operator new(size_t bytes){
		cout << "------new test()------" << endl;
		int alloc = pos;
		pos += bytes;
		return (mem + alloc);
	};

	void operator delete(void *){
		cout << "------delete test()------" << endl;

	};

	void * operator new[](size_t bytes){
		cout << "------new test()------" << endl;
		int alloc = pos;
		pos += bytes;
		return (mem + alloc);
	};

	void operator delete[](void *){
		cout << "------delete test()------" << endl;

	};
};

int main()
{
	test * x = new test;

	delete x;

	x = new test[3];

	delete [] x;
}


对new 和delete 函数的重载能够用来检測 内存泄露的情况。



 










 


 


转载于:https://www.cnblogs.com/ldxsuanfa/p/10510150.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值