類構造函數失敗,如何返回NULL

#include <string.h>
#include <stdio.h>
#include <string>
using namespace  std;

class Myclass
{
public:
	Myclass();
	void* operator new(size_t, char*);
	void operator delete(void*);
	int b_4;
};


//size表示new後面的對象大小 args是表示參數
void* Myclass::operator new(size_t size, char* args)
{
	void* storage = malloc(size);
	if(NULL == storage) {
		throw "allocation fail : no free memory";
	}
	memset(storage, 0x0, size);
	printf("opeartor new!\n");
	printf("args:[%s]\n", args);
	printf("type size is:[%d]\n", size);
	retrun storage;
	//添加邏輯 處理失敗
	//return NULL;
}

Myclass::Myclass()
{
	printf("constructor.\n");
}
void Myclass::operator delete(void*)
{
	//free(storage):
}


int main()
{ 
	
	char yx[] = "yongxin";

	Myclass *my = new(yx) Myclass();
	printf("my:%x\n", my);
	system("pause");
	return 0;
}



//place new是opeartor new的一種特例哦
//char buf[50];
//X *x = new (buf)X;
//new後面的參數是一個緩存地址
//而opreator new 後面不一定是地址


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章