#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 后面不一定是地址
类构造函数失败,如何返回NULL
最新推荐文章于 2020-02-15 14:11:57 发布