Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would a new[] expression ever invoke a destructor?

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.

like image 360
thb Avatar asked Mar 22 '19 20:03

thb


People also ask

What happens when a destructor is invoked?

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() .

What is the purpose of a destructor?

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.

How many times destructor is invoked?

Why is the destructor being called three times?

What out of the listed activities invoke the destructor for an object in C++?

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.


1 Answers

If construction of any object in the buffer throws an exception, the previously constructed objects must be destructed. That requires an available destructor.

like image 50
StoryTeller - Unslander Monica Avatar answered Oct 05 '22 18:10

StoryTeller - Unslander Monica