c++c++11default-constructordefault-initialization

Initializing an array of objects created on the heap


Given the non trivial data structure:

claas MyClass
{
public:
  MyClass():x(0), p(nullptr)
  {}

private:
  int x;
  int* p;
};

Is there any guarantee provided by the c++ specification that the default constructor will be called for each instance of MyClass in the array pointed by the ptr?

    int main()
    {
      MyClass* ptr = new MyClass[5];
    }

Solution

  • Is there any guarantee provided by the c++ specification that the default constructor will be called for each instance of MyClass in the array pointed by the ptr?

    Yes, it is guaranteed as explained below.

    From new expression's documentation:

    ::(optional) new new-type initializer(optional)   (2)     
    

    The object created by a new-expression is initialized according to the following rules:

    • If type or new-type is an array type, an array of objects is initialized.

      • If initializer is absent, each element is default-initialized.

    And further from default initialization documentation:

    new T       (2)
    

    Default initialization is performed in three situations:

    2) when an object with dynamic storage duration is created by a new-expression with no initializer;

    Moreover,

    The effects of default initialization are:

    • if T is an array type, every element of the array is default-initialized;

    (emphasis mine)

    Note the very last statement which says that "every element is default-initializaed" which means(in your example) the default constructor will be called as per bullet point 1:

    if T is a (possibly cv-qualified) non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;


    This means that it is guaranteed that the default constructor will be called in your example.