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]; }
Yes, it is guaranteed as explained below.
From new expression's documentation:
And further from default initialization documentation:
Moreover,
(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:
This means that it is guaranteed that the default constructor will be called in your example.