#include <iostream>
#include <stdlib.h>
using namespace std;
class Foo {
public:
int _id;
long _data;
string _str;
public:
Foo():_id(0) {
cout << "default ctor. this=" << this << " id=" << _id << endl;
}
Foo(int i):_id(i) {
cout << "ctor. this=" << this << " id=" << _id << endl;
}
//non virtual
~Foo() {
cout << "dtor. this=" << this << " id=" << _id << endl;
}
static void* operator new(size_t size);
static void operator delete(void* pdead, size_t size);
static void* operator new[](size_t size);
static void operator delete[](void* pdead, size_t size);
};
void* Foo::operator new(size_t size){
Foo* p = (Foo*)malloc(size);
cout << "Foo::operator new(), size= " << size << endl;
return p;
}
void Foo::operator delete(void* pdead, size_t size){
cout << "Foo::operator delete(), pdead= " << pdead << " size= " << size << endl;
free(pdead);
}
void* Foo::operator new[](size_t size){
Foo* p = (Foo*)malloc(size);
cout << "Foo::operator new[](), size= " << size << endl;
return p;
}
void Foo::operator delete[](void* pdead, size_t size){
cout << "Foo::operator delete[](), pdead= " << pdead << " size= " << size << endl;
free(pdead);
}
int main() {
cout << "sizeof(string) " << sizeof(string) << endl;
cout << "sizeof(Foo) " << sizeof(Foo) << endl;
Foo* p = new Foo(7);
delete p;
cout << endl;
Foo* pArray = new Foo[5];
delete []pArray;
cout << "---------------------------------------------------" << endl;
p = ::new Foo(7);
::delete p;
cout << endl;
pArray = ::new Foo[5];
::delete []pArray;
return 0;
}
Foo* p = new Foo(7);
delete p;
Foo* pArray = new Foo[5];
delete []pArray; 若无members 就调用 globals
p = ::new Foo(7);
::delete p;
pArray = ::new Foo[5];
::delete []pArray; 这样调用(也就是写上global scope operator::会逃过前面所有overloaded functions强迫使用global version)
都没有进入重载的operator new(),operator delete(),operator new[](),operato[]()