When object is created in the heap, it (new) does two things.
1: calls operator new
2: calls constructor to initialize the obejct.
I am trying to create array of objects, for example 4 objects , so it calls constructor and destructor 4 times that makes sense but it only calls one time operator new[] ?? why? Following is the code that i am trying to run.
#include <iostream>
using namespace std;
class test
{
public:
static void *operator new[] (size_t size)
{
cout<<"operaotor new called"<<endl;
return ::operator new[](size);
}
test()
{
cout<<"constructor called"<<endl;
}
~test()
{
cout<<"destructor called"<<endl;
}
};
int main()
{
test *k = new test[4];
delete []k;
}
operator new[]
is only there to allocate the necessary space, nothing else. Of course, it will do so only once, as anything else would be nonsens and wouldn't get a contiguous buffer. The size
parameter you're getting, in the case of new test[4]
, should be 4 * sizeof(test)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With