Are there any guarantees in C++ about the order in which array elements are constructed?
#include <iostream>
using namespace std;
struct A {
A() { cout << this << endl; }
};
int main()
{
cout << "[0] is " << new A[3];
}
prints out
0x602010
0x602011
0x602012
[0] is 0x602010
implying that the elements were constructed in the sequence [0], [1] and [2]. Is that order guaranteed by the language?
Yes, that's guaranteed by C++11 12.6/3 ([class.init]/3):
When an array of class objects is initialized (either explicitly or implicitly) and the elements are initialized by constructor, the constructor shall be called for each element of the array, following the subscript order
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