Reputation: 2778
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
Upvotes: 1
Views: 80
Reputation: 500327
What is likely happening is that the C++ library uses operator new
to allocate memory for its internal purposes. For example, writing to std::cout
could well trigger the allocation of some internal buffers, resulting in calls to the overloaded operator new
.
Upvotes: 3
Reputation: 2813
Something is wrong with your compilation:
Here it is called only once.
The Output is:
Hello
Calling New:
Calling Delete:
Or maybe others things calls it in background.
Upvotes: 0