Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ array elements order of construction

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?

like image 992
Benito Ciaro Avatar asked Sep 26 '13 14:09

Benito Ciaro


1 Answers

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

like image 109
Mike Seymour Avatar answered Sep 23 '22 08:09

Mike Seymour