Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does libstdc++'s std::vector<bool>::data do?

According to the standard, std::vector<bool> has no member function data(). However, the following snippet compiles fine with the latest GCC with libstdc++:

#include <vector>

int main () {
    std::vector<bool> v;
    v.data();
}

If we try to use the result, it turns out the return type is void.

Is this some gcc extension or a bug?
If the former is true, what does it do?

like image 696
Baum mit Augen Avatar asked Oct 24 '16 20:10

Baum mit Augen


People also ask

What is vector bool?

The vector<bool> class is a partial specialization of vector for elements of type bool . It has an allocator for the underlying type that's used by the specialization, which provides space optimization by storing one bool value per bit.

Whats wrong with std vector bool?

First, what's wrong with vector<bool> ? Because vector<bool> holds bits instead of bools, it can't return a bool& from its indexing operator or iterator dereference. This can play havoc on quite innocent looking generic code.

How do you create a Boolean vector?

If vector1 and vector2 are two vectors of the same length, then vector1 == vector2 outputs a vector of that same length. Element i of the vector created by vector1 == vector2 equals TRUE if vector1[i] == vector2[i] and equals FALSE otherwise. A vector in which every element is TRUE or FALSE is called a Boolean vector.


1 Answers

My /usr/include/c++/4.8/bits/stl_bvector.h has:

// _GLIBCXX_RESOLVE_LIB_DEFECTS
// DR 464. Suggestion for new member functions in standard containers.
// N.B. DR 464 says nothing about vector<bool> but we need something
// here due to the way we are implementing DR 464 in the debug-mode
// vector class.
void
data() _GLIBCXX_NOEXCEPT { }

In /usr/include/c++/4.8/debug/vector I see the declaration:

using _Base::data;

So that seems to be the reason: the debug version of std::vector<bool> wouldn't compile unless std::vector<bool>::data existed.

like image 144
Brian Bi Avatar answered Sep 21 '22 09:09

Brian Bi