学习《C++ Primer》,讲到new的expression和operator new函数的关系,于是想到让new的expression使用自定义的operator new函数。代码如下
//#include <new>
#include <iostream>
using std::cout;
using std::endl;
class Foo
{
public:
Foo(): m(0){cout << "Foo::Foo()" << endl;}
int m;
};
void* operator new(size_t _Count) throw(std::bad_alloc)
{
cout << "my own operator new, _Cout is " << _Count << endl;
return malloc(_Count);
}
int main(int argc, char *argv[])
{
Foo *p = new Foo;
::operator new(3);
return 0;
}
在VC2005里编译运行,O.K.,挺高兴。
忽然觉得用malloc不够“C++”的风格,这才发现没办法使用原来标准库里的::operator new函数了(把malloc换成operator new,则程序就死循环了)。各位大侠有什么高明的方法吗?