#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
C++内存管理
最新推荐文章于 2020-01-08 10:50:11 发布
本文介绍了一个C++类中自定义new和delete运算符的方法。通过重载这些运算符,可以在分配和释放内存时进行初始化和特定操作,如使用malloc进行内存分配并用memset进行清零。此外,还展示了如何传递额外参数到自定义new运算符。
855

被折叠的 条评论
为什么被折叠?



