1. 程式人生 > >走進C++程序世界-----operator new delete 重載

走進C++程序世界-----operator new delete 重載

net .net mail RM 釋放空間 pos mar alloc eas

?在C++ 的世界裏,new 和delete 是keyword。而在C的世界裏相相應的malloc和free是函數,關鍵C++的new和delete分析,詳見前面的章節。這裏就不在過多的介紹了。鏈接。

以下來研究下關於new 和delete的重載。

?1、對照使用重載和未使用重載

?未使用“

/*File : operator_new.cpp
 *Auth : sjin
 *Date : 2014-04-27
 *Mail : [email protected]
 */

#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 : [email protected]
 */

#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 : [email protected]
 */

#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 函數的重載能夠用來檢測 內存泄露的情況。



?










?


?


走進C++程序世界-----operator new delete 重載