I'm trying to understand how the placement new/delete works and hence I've written the following program:
# 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;
}
For the above code, I'm getting the below output:
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:
In the output, it is seen that operator new is called multiple times (even though only one instance of Test is created) and delete is called fewer number of times.
Can anybody please suggest whats wrong here?
Thanks
operator newshould only get and return memory, not call placement new on it.return new (malloc(size)) Test() ;this line is horribly wrong, it should bereturn malloc(size);. Or totally correctly you should echeck for nullptr and throw a bad_alloc