为什么std :: vector< bool>没有.data()? [英] Why does std::vector<bool> have no .data()?

查看:210
本文介绍了为什么std :: vector< bool>没有.data()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11 23.3.7/1中指定的std::vector<bool>的特殊化没有声明data()成员(例如,提到的).

问题是:为什么std::vector<bool>没有.data()?这就是为什么bool的向量没有连续存储在内存中的问题,这是一个非常相同的问题.不这样做有什么好处?

为什么不能返回指向bool数组的指针?

解决方案

为什么std :: vector没有.data()?

因为 std::vector<bool> 将多个值存储在1个字节中. /p>

像压缩存储系统一样思考它,其中每个布尔值都需要1位.因此,与其在每个内存块中只有一个元素(每个数组单元中只有一个元素),不如说是这样的内存布局:

假设您要索引一个块以获取一个值,您将如何使用运算符[]?它不能返回bool&(因为它将返回一个字节,该字节存储多个bools),因此您不能为其分配bool*.换句话说,bool *bool_ptr =&v[0];不是有效代码,并且会导致编译错误.

此外,正确的实现可能没有这种专长,并且不进行内存优化(压缩).因此,data()将不得不根据实现方式复制到预期的返回类型(或者标准应强制优化而不是仅仅允许优化).

为什么不能返回指向布尔数组的指针?

因为>不是 存储为布尔数组,因此无法以简单的方式返回任何指针.它可以通过将数据复制到数组中并返回该数组来做到这一点,但这是一种设计选择,不要这样做(如果这样做,我认为这对于所有容器都是data(),这会产生误导)

不这样做有什么好处?

内存优化.

通常将内存使用量减少8倍,因为它在单个字节中存储了多个位.确切地说, CHAR_BIT 少一倍.

The specialisation of std::vector<bool>, as specified in C++11 23.3.7/1, doesn't declare a data() member (e.g. mentioned here and here).

The question is: Why does a std::vector<bool> have no .data()? This is the very same question as why is a vector of bools not stored contiguously in memory. What are the benefits in not doing so?

Why can a pointer to an array of bools not be returned?

解决方案

Why does a std::vector have no .data()?

Because std::vector<bool> stores multiple values in 1 byte.

Think about it like a compressed storage system, where every boolean value needs 1 bit. So, instead of having one element per memory block (one element per array cell), the memory layout may look like this:

Assuming that you want to index a block to get a value, how would you use operator []? It can't return bool& (since it will return one byte, which stores more than one bools), thus you couldn't assign a bool* to it. In other words bool *bool_ptr =&v[0]; is not valid code, and would result in a compilation error.

Moreover, a correct implementation might not have that specialization and don't do the memory optimization (compression). So data() would have to copy to the expected return type depending of implementation (or standard should force optimization instead of just allowing it).

Why can a pointer to an array of bools not be returned?

Because std::vector<bool> is not stored as an array of bools, thus no pointer can be returned in a straightforward way. It could do that by copying the data to an array and return that array, but it's a design choice not to do that (if they did, I would think that this works as the data() for all containers, which would be misleading).

What are the benefits in not doing so?

Memory optimization.

Usually 8 times less memory usage, since it stores multiple bits in a single byte. To be exact, CHAR_BIT times less.

这篇关于为什么std :: vector&lt; bool&gt;没有.data()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆