Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new[] if element default constructor can throw?

Tags:

c++

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?

like image 377
Kohn1001 Avatar asked Oct 29 '13 11:10

Kohn1001


People also ask

Does new array call constructor?

When you use new[] each element is initialized by the default constructor except when the type is a built-in type.

Is it OK to throw exception in constructor in C++?

Don't throw exceptions in constructors.

Does New invoke constructor?

When you create a new object, memory is allocated using operator new function and then the constructor is invoked to initialize the memory.

What is constructor explain default constructor with example?

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.


1 Answers

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.

like image 154
Kerrek SB Avatar answered Oct 04 '22 04:10

Kerrek SB