c++flexible-array-member

Flexible array as a class member


GCC G++ 9

This code:

   class foo {
     int bar[] = {111, 123};
   };

produces an error about initializer for flexible array. But this one:

   class foo {
     int bar[2] = {111, 123};
   };

compiles as normal. Any workaround for not counting the values I put in?


Solution

  • Unlike in a function where you can do

    int foo[] = { 1, 2, 3 };
    

    and the compiler will deduce the size of foo from the initializer, when you do

    struct bar
    {
        int foo[] = { 1, 2, 3 };
    };
    

    what you really have is

    struct bar
    {
        bar() : foo{ 1, 2, 3 } {}
        int foo[];
    };
    

    and that can't work because C++ does not allow flexible arrays like C does.

    That leaves you with two options. The first is you specify the size. This isn't the greatest solution since it could introduce bugs but it will save you from dynamic initialization. The second option is to use a type that, at run time, can be initialized from the list. A std::vector for instance would fill that requirement nicely. Yes, there will be a dynamic memory allocation, but since std::vector is an RAII type, you don't need to worry about it and can use the default constructors and destructor.