C++ 是否保证数组元素的构造顺序?
#include <iostream>
using namespace std;
struct A {
A() { cout << this << endl; }
};
int main()
{
cout << "[0] is " << new A[3];
}
打印出来
0x602010
0x602011
0x602012
[0] is 0x602010
暗示元素是按序列 [0]、[1] 和 [2] 构造的。语言保证该顺序吗?
最佳答案
是的,这是由 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
关于C++数组元素的构造顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19030789/