2

I have the following code:

#include <vector>

struct TestStruct {
    std::vector<float> float_vect;
    std::vector<bool> bool_vect;
};

void func(const TestStruct & test)
{
    const float * p1 = test.float_vect.data();  //<---   this line works fine
    const bool * p2 = test.bool_vect.data();    //<---   on this line error happens
}

int main()
{
    TestStruct test;
    func(test);
}

Error message:

passing 'const std::vector' as 'this' argument of 'void std::vector::data() [with _Alloc = std::allocator]' discards qualifiers [-fpermissive]

data() method of std::vector have const specified.

Why this method works fine on float vector, and raises an error on boolean vector ?

Caduchon
  • 4,574
  • 4
  • 26
  • 67
Serbin
  • 803
  • 12
  • 27
  • 1
    I don't think the standard specifies that there is any `std::vector::data()` member function at all. – You Sep 29 '17 at 10:40
  • I never had a closer look at it, but [std::vector](http://en.cppreference.com/w/cpp/container/vector_bool) says `[...]std::vector is a possibly space-efficient specialization of std::vector for the type bool.[...]` and `[...]The manner in which std::vector is made space efficient (as well as whether it is optimized at all) is implementation defined.[...]` so the memory layout of `data()` would be not known. – t.niese Sep 29 '17 at 10:41
  • 1
    I don't see `data` method available for [`std::vector`](http://en.cppreference.com/w/cpp/container/vector_bool). – Algirdas Preidžius Sep 29 '17 at 10:42
  • 1
    Possible duplicate of [What does libstdc++'s std::vector::data do?](https://stackoverflow.com/questions/40227414/what-does-libstdcs-stdvectorbooldata-do) – You Sep 29 '17 at 10:42

2 Answers2

3

vector<bool> is a specialization of a good old vector<T> and it may be implemented differently from ordinary vector (e.g. some space-saving optimizations may be employed). Side-effect of such design is that it does not always behave as ordinary vector (many consider vector<bool> to be broken because of that).

For example, the reference at http://en.cppreference.com/w/cpp/container/vector_bool does not mention vector<bool>::data() at all. Therefore - you should not use it when using vector with type bool. The fact that you don't get an error similar to method not found is - in your case - just a matter of how vector<bool> is implemented by your compiler.

lukeg
  • 4,189
  • 3
  • 19
  • 40
1

std::vector<bool> is a template specialization of the class std::vector<T> in the STL. In order to use less memory, the boolean values are stored by 8 in a byte. It means there is no direct data accessible as you expect because the class doesn't store it in the same way than for other types.

Look at the doc :

The specialization has the same member functions as the unspecialized vector, except data, emplace, and emplace_back, that are not present in this specialization.

Caduchon
  • 4,574
  • 4
  • 26
  • 67