New array allocations

This is a compiler bug.

By using operator new without a constant defined type size MSVC compiler will call the class object constructor and destructor as many times as explicitly specified at initializer list and/or array size.

#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;
}

As stated will call as explicitly specified point ctor once.

This can be asserted by: point* ptr = new point[x]{point(), point()};

  • MSVC Output: ctor ctor dtor dtor dtor.
  • GCC: ctor ctor ctor dtor dtor dtor (which should be guaranteed)

And even a throwable array out of bound exception UB: point* ptr = new point[x]{point(), point(), point(), point(), point() }; follows the behavior.

  • MSVC Output: ctor ctor ctor ctor ctor dtor dtor dtor.
  • GCC: terminate called after throwing an instance of 'std::bad_array_new_length'

Too many initializers is correctly detected if the defined size is constant. i.e const int x = 3 or constexpr int x = 3