I know that, new operator will call the constructor of class.
But how it's happening, what is ground level techniques used for this.
Here is how I imagine it:
T* the_new_operator(args)
{
void* memory = operator new(sizeof(T));
T* object;
try
{
object = new(memory) T(args); // (*)
}
catch (...)
{
operator delete(memory);
throw;
}
return object;
}
(*) Technically, it's not really calling placement-new, but as long as you don't overload that, the mental model works fine :)
It's not really the new operator that calls the constructor. It is more the compiler that translate the following line:
MyClass * mine = new MyClass();
Into the following:
MyClass * mine = malloc(sizeof(MyClass)); // Allocates memory
mine->MyClass(); // Calls constructor
With other error handling code that other answers have noted.
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