我试图了解放置 new/delete 的工作原理,因此我编写了以下程序:
# include <iostream>
# include <cstdlib>
using namespace std;
class Test {};
void * operator new (size_t size) throw (std::bad_alloc){
cout<<"Calling New:"<<endl;
return new (malloc(size)) Test() ;
}
void operator delete (void *ptr) throw () {
cout<<"Calling Delete:"<<endl;
free (ptr) ;
}
int main ()
{
cout<<"Hello"<<endl;
Test *ptr = new Test () ;
delete ptr ;
return 0;
}
对于上面的代码,我得到以下输出:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling Delete:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling Delete:
Hello
Calling New:
Calling Delete:
在输出中,可以看到 operator new 被多次调用(即使只创建了一个 Test 实例),而 delete 被调用的次数更少。
有人可以建议这里有什么问题吗?
谢谢