C++数组元素的构造顺序

标签 c++ arrays constructor

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/

相关文章:

c++ - GetDiBits:BITMAPINFOHEADER 中传递的不同维度

c++ - 为什么++(后增量运算符)不能是左值?

c++ - QByteArray 的十六进制值如何在不转换为 ASCII 字符的情况下显示

javascript - 返回一个不同于 ES6 类的值

c++ - 如何在实例化时使用用户输入在类构造函数中初始化私有(private) char *

c++ - GLFW3的glfwWindowHint函数中framebuffer的几个组件bitdepth的作用是什么?

c++ - 如何获取蓝牙HID设备的MAC地址?

Java for循环中数组的最小元素

php - 将列表从 php 或 xmlhttp.responseText 传递到 javascript

javascript - 根据索引控制主动构造函数