0

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];
    }
6
  • that the default constructor will be called for is there anything else you expect to happen here? Commented Oct 14, 2022 at 12:33
  • 5
    @sampath Yes there is. Commented Oct 14, 2022 at 12:35
  • You can also add a cout and test it yourself. Though that will only show you instead of guaranteeing. Commented Oct 14, 2022 at 12:36
  • 3
    @JasonLiam not really. That doesn't work to test whether the standard guarantees things. Commented Oct 14, 2022 at 12:36
  • @user253751 Ofcourse i know that. Commented Oct 14, 2022 at 12:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Useless Yes, I've added some more explanation at the end saying that since every element of the array is default-initialized, so as per point 1, the default constructor will be called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.