Why is the size of “std::vector” 16 Byte?

2019-03-26 11:08发布

问题:

I'm using memcpy to copy the content of std:vectors<> to primitve Arrays. For datatypes like int, float, double etc. it worked well. As I started to copy a boolvector I encountered a problem namely I got strange values.

First I started to make an test output for a float vector:

std::vector<float> test1 (3,0);

cout << "Sizeof test1[0] : " << sizeof(test1[0]) << endl
     << "Memoryaddress 0: " << &test1[0] << endl
     << "Memoryaddress 1: " << &test1[1] << endl
     << "Memoryaddress 2: " << &test1[2] << endl;

The output is:

Sizeof test1[0]: 4
Memoryaddress 0: 02793820
Memoryaddress 1: 02793824
Memoryaddress 2: 02793828

And this is what I expect. The float size is 4 Byte and the distance to the next float value is 4 Byte. When I do this for bool the output looks like this:

std::vector<bool> test (3,0);

cout << "Sizeof test[0]: " << sizeof(test[0]) << endl
     << "Memoryaddress 0: " << &test[0] << endl
     << "Memoryaddress 1: " << &test[1] << endl
     << "Memoryaddress 2: " << &test[2] << endl;

The output is:

Sizeof test[0]: 16
Memoryaddress 0: 011EF94C
Memoryaddress 1: 011EF93C
Memoryaddress 2: 011EF92C

Why is the size of bool 16 Byte? It seems like a total overkill to me. Are there explanations for this?

回答1:

Unlike other specialisations of vector, vector<bool> does not manage a dynamic array of bool objects. Instead, it is supposed to pack the boolean values into a single bit each.

Since individual bits are not addressable, test[0] cannot simply be a reference to bool. Instead, it is an class type vector<bool>::reference that can be converted to bool (to get the value), and assigned from bool (to modify the vector element).

This means that vector<bool> doesn't entirely meet the requirements of a standard container, and can't be used if you need references or pointers to its elements. If you do require a "real" container with addressable elements, consider vector<char> or deque<bool> instead.



回答2:

std::vector<bool> is a specialized version of vector, which is optimizes for space.

  • The storage is not necessarily an array of bool values, but the library implementation may optimize storage so that each value is stored in a single bit.
  • Elements are not constructed using the allocator object, but their value is directly set on the proper bit in the internal storage.

More information: http://www.cplusplus.com/reference/vector/vector-bool/