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

前端 未结 1 803
借酒劲吻你
借酒劲吻你 2020-12-18 19:15

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

1条回答
  •  有刺的猬
    2020-12-18 19:53

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

    Because std::vector 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 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.

    0 讨论(0)
提交回复
热议问题