[英]Why is the size of “std::vector<bool>” 16 Byte?
I'm using memcpy to copy the content of std:vectors<> to primitve Arrays. 我正在使用memcpy将std:vectors <>的内容复制到primitve Arrays。 For datatypes like int, float, double etc. it worked well. 对于像int,float,double等数据类型,它运行良好。 As I started to copy a boolvector I encountered a problem namely I got strange values. 当我开始复制一个boolvector时,我遇到了一个问题,即我得到了奇怪的值。
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. 浮点大小为4字节,到下一个浮点值的距离为4字节。 When I do this for bool the output looks like this: 当我为bool执行此操作时,输出如下所示:
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? 为什么bool 16 Byte的大小? It seems like a total overkill to me. 这对我来说似乎是一种矫枉过正。 Are there explanations for this? 对此有解释吗?
Unlike other specialisations of vector
, vector<bool>
does not manage a dynamic array of bool
objects. 与vector
其他特化不同, vector<bool>
不管理bool
对象的动态数组。 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
. 由于单个位不可寻址,因此test[0]
不能简单地作为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). 相反,它是一个类类型vector<bool>::reference
,可以转换为bool
(获取值),并从bool
分配(以修改vector元素)。
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. 这意味着vector<bool>
并不完全满足标准容器的要求,如果需要引用或指向其元素,则无法使用它。 If you do require a "real" container with addressable elements, consider vector<char>
or deque<bool>
instead. 如果确实需要具有可寻址元素的“真实”容器,请考虑使用vector<char>
或deque<bool>
。
std::vector<bool>
is a specialized version of vector, which is optimizes for space. std::vector<bool>
是std::vector<bool>
的专用版本,它优化了空间。
More information: http://www.cplusplus.com/reference/vector/vector-bool/ 更多信息: http : //www.cplusplus.com/reference/vector/vector-bool/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.