-1

I required your help for a very strange behaviour that I can't understand.

I wrote a simple usage of vector.data :

    void* ptr = NULL; // really initialized somewhere else
    bool* boolPtr = NULL;
    boolPtr = ((std::vector<bool>*)ptr)->data();

and when I compile (with -std=c++17) I got the error

void value not ignored as it ought to be

I try a lot a things but it seems that each time I call, from a casted vector (from void*), the data() method return a void instead of a bool*.

What did I miss ?

zzDiego
  • 37
  • 1
  • 8
  • 4
    A `vector` is a special type of vector and there is no API to get at the underlying buffer. – NathanOliver Feb 17 '22 at 15:49
  • 2
    Whenever you do a C-style cast in C++ (like you do with `(std::vector*)ptr`) you should take that as a sign that you're doing something *wrong!* A vector is *not* equivalent to an array, other than some of the vectors operations mimic that of an array. To make matters worse, `std::vector` is a *specialization* that is unlike any other `std::vector`. – Some programmer dude Feb 17 '22 at 15:50
  • 2
    Duplicate? [What happens when you call data() on a std::vector?](https://stackoverflow.com/questions/16568986/what-happens-when-you-call-data-on-a-stdvectorbool) – Drew Dormann Feb 17 '22 at 15:52
  • 1
    Also, the way a programmer attempts to figure out a problem like this is to break up that line of code into multiple statements. `((std::vector*)ptr)->data();` -- Is it the cast that is the issue? Is it the call to `data()` that is the issue? You don't know, because you are doing multiple things on one line. What you should have done is do the cast and assign it to a variable -- see if the compiler is issuing a warning/error for that line. Then take that variable and use it to call `data()`, etc. I see too many programmers munge things on one line trying to figure out what's wrong. – PaulMcKenzie Feb 17 '22 at 15:54
  • 1
    @PaulMcKenzie Good advice in general. Unfortunately not just for any case with a C-style cast, as that tells the compiler "Hands off, I know what I'm doing!" even if that's not true (as is the case here). – Some programmer dude Feb 17 '22 at 15:56
  • For such cases, I have a `struct Bool { bool value; }` at hand. `std::vector` behaves as `std::vector` for every other type (except `bool`). (I gave it a conversion operator to `bool` (among other methods) so that it can be conveniently used like a `bool`.) – Scheff's Cat Feb 17 '22 at 15:59

1 Answers1

2

vector<bool> is not a proper vector. As weird as that sounds, that's the way it is. It can't give you a pointer to its internal bool array, because it doesn't have one, since it stores the values packed into single bits.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157