c++;重载new和delete后,new ('d')BM()是什么结构?(在线)

来源:百度知道 编辑:UC知道 时间:2024/07/07 09:59:19
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "stddef.h"

class BM
{
int i;
public:
void * operator new (size_t size)
{
cout<<size<<endl;
static char *ch=new char[size];
*ch='z';
return ch+1;
}
void * operator new (size_t size,char c)
{
static char *ch=new char[size];
*ch=c;
return ch+1;
}
void operator delete(void *p)
{
char *ch=static_cast<char*>(p);
cout<<"t1="<<*(ch-1)<<endl;
delete[](ch-1);
}
};

int _tmain(int argc, _TCHAR* argv[])
{
BM *t1=new BM;
delete t1;
//下面这句是什么形式,没有对应的函数啊,书上说调用第二个new,可是参数是怎么匹配的?
BM *t2=new('d')BM();
delete t2;
return 0;
}

看这个函数
void * operator new (size_t size,char c)
{
static char *ch=new char[size];
*ch=c;
return ch+1;
}

“d”就是char c,而因为BM *t2是一个指针,没有指定new的大小,故size_t size是缺省