为什么是&QUOT大小;的std ::矢量&lt;&布尔GT;&QUOT; 16字节? [英] Why is the size of "std::vector<bool>" 16 Byte?
问题描述
我使用的memcpy性病的内容复制:矢量&lt;?>到primitve阵列。对于喜欢整数,浮点,双等数据类型,效果不错。当我开始复制boolvector我遇到了一个问题,即我有奇怪的值。
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;
输出是:
Sizeof test1[0]: 4
Memoryaddress 0: 02793820
Memoryaddress 1: 02793824
Memoryaddress 2: 02793828
这是我所期望的。浮球大小为4字节和下一个浮点值的距离为4字节。当我这样做对布尔输出看起来是这样的:
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;
输出是:
Sizeof test[0]: 16
Memoryaddress 0: 011EF94C
Memoryaddress 1: 011EF93C
Memoryaddress 2: 011EF92C
为什么是布尔16字节的大小?这似乎是一个总矫枉过正给我。有没有解释这个?
Why is the size of bool 16 Byte? It seems like a total overkill to me. Are there explanations for this?
推荐答案
与载体的其他专业
,矢量&lt;布尔&GT;
不管理布尔
对象的动态数组。相反,它被认为布尔值打包成一个单一的比特的每个
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.
由于各个位不寻址,试验[0]
不能简单地是布尔
的参考。相反,它是一个类类型矢量&lt;布尔&GT; ::参考
可转换为布尔
(获取值),并从布尔
分配(修改矢量元素)。
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).
这意味着矢量&lt;布尔&GT;
不完全符合标准的容器的要求,并不能用于如果需要引用或指针的元素。如果您还需要具有寻址元素的真实的集装箱,考虑矢量&lt;字符&GT;
或双端&LT;布尔&GT;
而不是
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.
这篇关于为什么是&QUOT大小;的std ::矢量&lt;&布尔GT;&QUOT; 16字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!