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.
std::vector
. C++ needs to know the exact size of a structure in advance. You can't make it up as you go. – Trappingsstatic constexpr int bar[] = {111, 123};
count as a flexible array member? It's probably unusable for OP, but still. – Lorrainelorrayne