新的数组分配

Den*_*cor 6 c++ arrays new-operator

所以我有这个名为point的类,只是为了在每次构造和销毁对象时登录到控制台。我做了以下事情:

#include <iostream>

struct point{
    point() {
        std::cout << "ctor\n";
    }
    ~point() {
        std::cout << "dtor\n";
    }
};
    int main(){
    int x = 3;
    point* ptr = new point[x]{point()};
    delete[] ptr;
}
Run Code Online (Sandbox Code Playgroud)
ctor
dtor
dtor
dtor
Run Code Online (Sandbox Code Playgroud)

This ended up calling the constructor just once, and the destructor 3 times, why? I know that this is bad, probably ub, but i would like to understand why. This other allocations give me the "expected" output:

ctor
dtor
dtor
dtor
Run Code Online (Sandbox Code Playgroud)
ctor
ctor
ctor
dtor
dtor
dtor
Run Code Online (Sandbox Code Playgroud)

Im using visual studio 19 latest version.

Vin*_*rta 3

这是一个编译器错误。

通过使用没有常量定义类型大小的运算符 new,MSVC 编译器将调用类对象构造函数和析构函数,次数与初始值设定项列表和/或数组大小中显式指定的次数相同。

#include <iostream>

struct point {
    point() {
        std::cout << "ctor\n";
    }
    ~point() {
        std::cout << "dtor\n";
    }
};
int main() {
    int x = 3;
    point* ptr = new point[x]{point()};
    delete[] ptr;
}
Run Code Online (Sandbox Code Playgroud)

如前所述,将调用明确指定的 pointctor 一次。

这可以通过以下方式断言:point* ptr = new point[x]{point(), point()};

  • MSVC 输出:ctor ctor dtor dtor dtor.
  • GCC:(ctor ctor ctor dtor dtor dtor应该保证)

甚至可抛出的数组越界异常 UB:point* ptr = new point[x]{point(), point(), point(), point(), point() };也会遵循该行为。

  • MSVC 输出:ctor ctor ctor ctor ctor dtor dtor dtor.
  • 海湾合作委员会:terminate called after throwing an instance of 'std::bad_array_new_length'

如果定义的大小是常量,则可以正确检测到过多的初始值设定项。即const int x = 3constexpr int x = 3