Is an empty vector the size of its struct?

2019-08-20 07:35发布

问题:

Say I have a struct like this:

struct vertexNodeInfo
{
    unsigned char level;
    int node;
    double leaf;
};

If I then had this:

vector<vertexNodeInfo> node;

How big (memory-wise, not .size) would the empty vector be, before any push_back? Would it be exactly the same size (again, in terms of memory) as vector<int> node;?

回答1:

There's no requirement. Even more, it's a poorly formulated question.

The .size of the vector would be 0, because it has no elements.

The sizeof isn't affected the number of elements, and is typically large enough to contain one or two of pointers to the type (which can vary in size themselves, so there's no guarantee the sizeof(vector<vertexNodeInfo>) and sizeof(vector<int>) are equal), the size and capacity.



回答2:

As Luchian says, it is likely but not required that sizeof(vector<int>) == sizeof(vector<vertexNodeInfo>).

Furthermore, I don't believe the standard makes any requirement as to the capacity of a default-initialized vector:

Initial capacity of vector in C++

So it's permitted to have a capacity of 10, meaning that it has allocated enough memory for 10 elements up front. Then the size of this allocation would of course depend on the size of the elements. You don't exactly define what you mean by "how big, memory-wise", but if you mean to include dynamic allocations then this would be one.

I don't think that would be a very good implementation of vector, but it conforms to the standard.