Search code examples
c++gcc-warning

warning: non-constant array size in new, unable to verify length of initializer-list


I face a problem similar to this one.

int j = 6;
int *k = new int[j]{4};

The warning is :

warning: non-constant array size in new, unable to verify length 
of initializer-list [enabled by default]

I face only a warning, no errors and I run with -std=gnu++11

Plus, I want the constructor called for every instance. If I print the array values, all


Solution

  • The problem is exactly what the compiler is telling you.

    The dimension is known only at runtime, so you may only use runtime functionality, such as:

    std::vector<int> v(j, 4);
    // `v` contains `j` ints, all initialised to `4`
    

    If you have an element type that cannot be default-constructed, you may construct the elements in-place:

    std::vector<T> v;
    v.reserve(j);
    for (size_t i = 0; i < j; i++)
       v.emplace_back(ctor-args-here);
    

    You could probably also use an initializer list:

    std::vector<T> v{
       T(ctor-args-here), T(ctor-args-here), T(ctor-args-here),
       T(ctor-args-here), T(ctor-args-here), T(ctor-args-here)
    };
    

    and the objects will be moved or, at worst, copied.

    The point here is that vector elements don't need to be default-constructible.

    (Unfortunately I'm not aware of a way to do this without the loop or code repetition.)