From the C++17 standard (draft here), [expr.new]:
If the new-expression creates an object or an array of objects of class type, access and ambiguity control are done for the allocation function, the deallocation function, and the constructor. If the new-expression creates an array of objects of class type, the destructor is potentially invoked.
Why would new[]
invoke a destructor? It's new, after all. It isn't delete.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
Why is the destructor being called three times?
Destructor function is automatically invoked when the objects are destroyed. It cannot be declared static or const. The destructor does not have arguments. It has no return type not even void.
If construction of any object in the buffer throws an exception, the previously constructed objects must be destructed. That requires an available destructor.
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