new delete 为表达式。这个过程不能重载,但是分解的步骤可以重载。
String* ps = newe String("Hello")
分解为:
String* ps;
void* mem = operator new(sizeof(String));
ps = static_cast<String*>(mem);
ps->String::String("Hello")
delete ps;
分解为:
String::~String(ps);
Operator delete(ps)
(一):这个影响的范围非常大
重载::operator new,::operator delete
::operator new[],::operator delete[]
void* myAlloc(size_t size)
{ return malloc(size); }
void myFree(void* ptr)
{ return free(ptr); }
inline void* operator new(size_t size)
{ return myAlloc(size): }
(二)重载member operator new/delete,只影响个类
class Foo{
public:
void* operator new[](size_t);
void operator delete[](void*,size_t);
//...
};
Foo* = new Foo[N]; ====>try{
void* mem = operator new(sizeof(Foo) * N); p = static_cast<Foo*>(mem);p->Foo::Foo();
}
...
delete [] p; ====> p->~Foo(); operator delete(p);