consider the following code:
example_t* a = new example_t[8];
class example_t
has default ctor that can throw, suppose construction of 5th element in array throws. Is there automatic call to destructor of the 4 first elements? Is it a well defined behavior?
When you use new[] each element is initialized by the default constructor except when the type is a built-in type.
Don't throw exceptions in constructors.
When you create a new object, memory is allocated using operator new function and then the constructor is invoked to initialize the memory.
A default constructor is a constructor created by the compiler if we do not define any constructor(s) for a class. Here is an example: public class Student { String firstName; String lastName; int age; public static void main(String args[]) { Student myStudent = new Student(); myStudent.
This is perfectly well-defined and well-behaved. All completely constructed subobjects are destroyed if the initialization of an object terminates with an exception, in reverse order of their construction. This is the same for arrays as it is for objects of user-defined type (think classes and class members).
Formally, we have C++11 15.2/2:
An object of any storage duration whose initialization or destruction is terminated by an exception will have destructors executed for all of its fully constructed subobjects (excluding the variant members of a union-like class), that is, for subobjects for which the principal constructor (12.6.2) has completed execution and the destructor has not yet begun execution.
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