Re: Zero-size array as struct member
Balog Pal <pasa@lib.hu> wrote:
How many times does this have to be explained?
If you need to instantiate the struct dynamically, there will be only
one malloc() call if the struct hack is used. However, if the struct hack
is not used, but std::vector or a raw array pointer is used instead, you
will need two allocations: One for the struct and another for the array
inside the struct.
What's so hard to understand in that?
Nothimg, it is just hard to believe that you actually meant to drag that
gremlin in an expert group and hope to get away with it.
We certainly do NOT do stuff like
new vector<int>
in real life, but have the vector as direct member, or it passed in, or
returned -- such code would hardly pass any review. So your "if"
situation only works on "paper" not reality.
How many times does this have to be explained? I just can't think how
I would explain it more clearly.
Ok, let me try once more. Assume you have this:
struct MyStruct
{
// Some other member variables here.
int size;
int array[0];
};
Then you need to allocate an instance of that struct dynamically (because
it has to survive the scope where it is being created). You do it like:
malloc(sizeof(MyStruct) + elements_amount * sizeof(int));
Please count the number of allocations being made. It's 1. Follow me so
far?
Ok, now consider the alternative:
struct MyStruct
{
// Some other member variables here.
std::vector<int> array;
MyStruct(int size): array(size) {}
};
Then when you need to allocate an instance of that struct dynamically,
you do it like:
new MyStruct(elements_amount);
Please count the number of allocations being made. It's 2 (one for the
struct itself, and one performed by std::vector).
Understand now?