r/ProgrammerHumor • • 10d ago

Meme cppAndItsVectorBooleans

Post image
3.4k Upvotes

214 comments sorted by

759

u/Semper_5olus 10d ago

I see how it would be nice to have that option -- perhaps in another type analogous to long vs short ints -- but isn't a bit all you need?

154

u/Drugbird 10d ago

Yes it is.

The main problem though is that vector<bool> behaves differently from any other data type. For instance, separate elements of the vector do not have unique addresses (because addresses are byte aligned).

This means that if you're doing anything with pointers on vectors, particularly if you're writing generic code (templates) then you very quickly run into cases where code is perfectly valid and correct for all types except for bool.

For instance, two adjacent elements in a vector are sizeof(T) apart in memory. Except when T=bool.

84

u/Semper_5olus 10d ago

Oh. So a bool is, for whatever reason, a different size if it's in a vector.

And that makes generic functions hard to write without checking for this specific case.

I didn't know that.

That is annoying.

64

u/bwmat 10d ago

The reason is that the people working on that part of the spec felt clever that day

But not clever enough to realize they should have specified it as std::dynamic_bitset (or something like that) instead

53

u/KaMaFour 10d ago

Programmer feeling clever should be a massive alarm bell for everyone

2

u/Interesting-Crab-693 8d ago

I'll remember that in my object oriented programing class next year!

16

u/pyxlmedia 10d ago

It's Not a vector nor does it store bools.

10

u/cinnamonjune 10d ago

What's worse is that the spec says that all vector<T> must return a T& if you do an operator[] on them, but of course vector<bool> can't do this because there are no bools to reference, so the solution they came up with was to say that operator[] on vector<bool> returns a vector<bool>::reference which is an internal class that implicitly decays to bool.

This means that you can do `my_vec[0] = true;`, and you can do `bool b = my_vec[0];`, but if you do `auto b = my_vec[0];` then things go horribly wrong because the type of `b` is not `bool` but instead becomes `vector<bool>::reference`.

1

u/SubstituteCS 10d ago

std::vector<bool> stores values using bits to shave off space.

In a vacuum this makes a lot of sense as 8 bools only take 1 byte instead of 8 bytes.

In practice, this causes a lot of headaches down the line and can easily lead to problems if someone isn’t aware of this specific nuance.

std::vector<T> is essentially an List<T> if you know C#

8

u/Abadabadon 10d ago

Oh damn really? So you couldn't do a pointer++ traversal across it?

14

u/Drugbird 10d ago

Not in a simple, straightforward way, no.

The main difficulty is that operator[] doesn't return a bool, but rather it returns some reference type that's convertible to a bool.

So if you do something like bool& begin = &vector[0]; bool& next = begin + 1;

That wouldn't work. I'm not even sure if that's a compilation error or if it just does the wrong thing. Vector<bool> is so cursed I do my best to never use it, but as a consequence I'm also not too familiar with it's details.

You can still use iterators though to iterate over the vector<bool>.

6

u/Hot-Category2986 9d ago

This is the explain I needed. Thank you.

1

u/zhaDeth 4d ago

Does that mean it constantly changes from "bit" bools to normal byte bools each time you use it?

1

u/Drugbird 3d ago

Yes. You can't have a normal bool pointer or reference into the vector, because there aren't any "regular" byte sized bools in there.

So any time you read a bool, it needs to create a new byte bool for the result. And when you write a bool, it needs to convert that bool to the correct bit flipping operation in the vector.

Particularly when you read a bool it's problematic because you can't e.g. take the address of it and expect to get an address inside the vector (which you can do with any other type of vector).

0

u/SirPriseTheEigth 10d ago

Tbf c++ does have a specific bool type (unlike c where it’s an int in disguise) - and if you want byte-aligned behaviour why not just use a vector<uint8_t> and bitshift/mask…also it’s the dynamically allocated version of a std::bitset so I think this actually makes sense as long as you know the quirks before making assumption…

9

u/Drugbird 10d ago

and if you want byte-aligned behaviour why not just use a vector<uint8_t> and bitshift/mask

Because we have a type system, and I don't want to have to abuse it just to get under some quirky behavior.

also it’s the dynamically allocated version of a std::bitset

Having a std::dynamic_bitset would be great. See e.g. the boost implementation.

Calling it a std::vector is the problem. It's too different from other std:: vectors, which is evident in that it has this huge exception status.

so I think this actually makes sense as long as you know the quirks before making assumption…

This is true for nearly every bad design in programming languages.

1

u/SirPriseTheEigth 10d ago

Well knowing the quirks is what keeps us in a job…

0

u/geekosas 10d ago

That's the way basic type array work... Only objects have references.

502

u/Bloodgiant65 10d ago

The problem is, especially with multithreading, etc. you can get into issues if you try to use a vector<bool>. It would have made much more sense to have the vector<bool> work like anything else, and introduce a std::bitset or similar for this kind of behavior.

265

u/Blue_Moon_Lake 10d ago

But because C++ never fixes past mistakes by breaking behavior, it'll never happen and they'll never do the sensible thing.

69

u/ImpulsiveBloop 10d ago

This is why I tend to just stick to C stdint types when I want specific data types while saving space. Consistent, configurable, and can be typedef-ed for clarity.

57

u/bwmat 10d ago

We just use vector<char> when we need it at work lol. 

45

u/Bloodgiant65 10d ago

Yeah I think that is pretty normal, unfortunately. Though to be explicit I would normally use uint8_t instead.

19

u/ImpulsiveBloop 10d ago

Yeah, I recall there being a difference between using char and uint8_t, too. But I can't be bothered to remember what. Overflow or something.

Unsigned char would be better. But that is more stuff to type out, and less clear on what it is imo.

26

u/nfitzen 10d ago edited 10d ago

From a C perspective, since IDK C++: char is defined to be the smallest addressable unit (in other words, a machine byte, which may be more than 8 bits on cursed hardware). Since CHAR_MAX >= 127 per the ISO C standard, it's probably the best thing to use for a hacky boolean type (of course, when bool doesn't work). uint8_t could also be used, but I feel like it communicates that we need 8 bits specifically rather than "the minimal amount the machine can address individually."

Edit: Also, unsigned char might be my first instinct, but it doesn't particularly matter. Any non-zero value is truthy to C. So I'd probably use char since I'm a fan of brevity.

7

u/ImpulsiveBloop 10d ago

Thank you. Just pretend I put in the effort to say this myself lol

6

u/bwmat 10d ago

If you're actually using the elements as booleans, only zero/non-zero matters, so char, signed char, unsigned char (yeah these are actually 3 separate types lol cpp) are all the same in this context

3

u/ImpulsiveBloop 10d ago

Yeah, I just meant in general. 

They are different, was my point, so they shouldn't be used interchangeably without consideration.

2

u/Scolmann 10d ago

Is there any behavior that breaks from them changing it to be bytes though?

It would take more memory but logically the code should be the same unless someone's doing bitcast BS with it

2

u/Blue_Moon_Lake 10d ago

It breaks multithreading.

6

u/TheThiefMaster 10d ago

No the current behaviour breaks multithreading

1

u/Blue_Moon_Lake 10d ago

Oh I read it incorrectly. I thought you asked what the bitset behavior was breaking.

Theoretically, it would break all code that try to handle it as a bitset by doing unsafe shitty read/write on the memory address.
But also, it would be extremely easy to do a "replace all" of vector<bool> to bitset when upgrading the code.

3

u/TheThiefMaster 10d ago

Can you manually read/write vector<bool>? I don't think it gives you data pointers at all

1

u/Blue_Moon_Lake 9d ago

Probably, but I never tried to write stupid code on purpose.

2

u/TheThiefMaster 9d ago

But my question highlights a problem with vector<bool> - it can't work in generic code that expects vector to be contiguous, addressable with T*, and have a .data() function that gives you that. Because it doesn't.

It doesn't even support &bool_vec[0] or &*begin() - because neither return actual references, but a reference proxy class. You can't take the address of an rvalue class, so it fails to compile entirely.

It's very well defended, but on the flip side it's incompatible with a lot of generic contexts because it doesn't have the same API as vector<T> generally, only a subset of it. Some of which seems to exist solely for there to be a common subset (like the nested reference type alias).

And the worst part is it explicitly has a member function on its nested "reference" type - so currently it can't be left unspecialised by an implementation.

→ More replies

1

u/adabsurdo 9d ago

Well breaking backwards compatibility just for esthetics / marginally practical reasons would be very stupid

0

u/SmoothTurtle872 10d ago

Simple: Vector<ByteBool>

47

u/Usual_Office_1740 10d ago

I'm not going to try defend the design of std::vector<bool> because it looks annoying to develop around, but this post got me wondering, so I Googled it. The underlying bit packing behavior and implementation is a remnant of C++98 with addons over years.

This design was set down before algoriths, iterators, ranges and during a time when concurrent programming was not the norm, if it existed at all.

I think this was mediocre idea that has aged like warm milk in a hot car. Not the terrible atrocious design people seem to make it out to be.

44

u/ben_g0 10d ago

The bit packing behaviour can be genuinely useful as it saves memory and uses the cache more effectively. I have no problem with the implementation in and of itself.

The problem IMO is just that it is mapped to the vector<bool> type, while it behaves differently than any other vector in some cases, and its elements aren't really bools and don't act exactly the same. Even without concurrent programming.
The "vector of bits" that vector<bool> actually is, is still very useful to have in the standard library, but would be better as a dedicated bitvector type. And vector<bool> should just act like any other vectors and just store a list of bools.

10

u/Usual_Office_1740 10d ago

That is a reasonable complaint about it. I've only been programming with C++ for a few years. This is one of the many things that gets thrown around a lot in the cpp subreddits but rarely seems to get the context it deserves. I had to learn to frame the comments about performance costs in the same way. There are valid points to what's being said with these comments but there is often more context that much more experienced devs don't specify and it changes how newer developers like myself view things.

I legitimately tried to avoid using std::function and lambdas at one point early on because I read that they were "slow".

9

u/ben_g0 10d ago

About performance costs there is indeed a lot of misinformation and misunderstanding about it on platform like Reddit. A lot of people seem to still think that more CPU cycles means slower, while CPU clock speed is rarely the bottleneck.

Also, it's perhaps a bit of a controversial opinion, but unless what you're doing is very performance critical, I think it's totally fine to use approaches that are not the most optimal but easier to use or that keep the code better organised. Development time often has much more strict limits than compute time, so I think that trades some performance to make it faster or easier to write the program is usually a good trade-off.

3

u/Usual_Office_1740 10d ago

I agree about your maybe controversial opinion on development time and ergonomics being more critical than performance time. I am pushing myself to just get something written and working instead of fixating on whether it is the optimal decision or even a good way to do it.

I read once that there have been studies done in grocery stores where often times to much variety for a single item can reduce the overall sales figures for that item. People can't decide what bag of Lays they want and opt for not getting Lays at all rather than making a decision between one of twenty options. Things sometimes sell better when there are only a few of the most popular flavors because the impulse buy response can kick in.

In C++ there are a dozen ways to do most things and there are trade-offs for most of them. I think I've been struggling with that for a while and your opinion is one way I'm leaning into to pushing passed this observation. Picking what looks to be the most ergonomic option or even just the first option that comes to mind.

As far as performance goes. I was definitely affected by what is said on reddit. I'm a newer developer. I don't want to write buggy sluggish software. If people say that's slow I don't want to do it that way. It wasn't really until I followed a book for writing a terminal based text editor called Kilo earlier this year that I stopped bothering to consider that at all. When I saw how snappy and responsive that project stayed even with the number of memcopies and system calls being done to a heap allocated representation of a 1000k line text document with syntax highlighting every key stroke that I began to get a sense of just how powerful modern CPU's are and how little my struggling with the few hundred extra assembly instructions I'm agonizing over will ever matter in the project's I'm capable of producing.

Those concerns are probably valid for some and I like to think those that make those comments are often people working in high performance industries were their experience has colored there thought process. It is slow to them based on the way they view things and the criteria they've had to learn to evaluate against over years of experience in an industry where that matters. That doesn't mean I should assume it's slow based on what I need.

1

u/ih-shah-may-ehl 7d ago

as it saves memory

You're already programming in C++. I would think that the memory savings of a very specific use of booleans isn't the big deal it is made out to be.

3

u/Scared_Accident9138 9d ago

Concurrency wasn't supported by the C++ standard itself back then, so there also wasn't a need to specify what happens in case of concurrent access

1

u/Usual_Office_1740 9d ago

Yeah. I got my first multi core processor in 2004ish? The standard would have been written in the late 90's. Was concurrent programming something the average developer even considered?

1

u/Scared_Accident9138 9d ago

Wasn't the Linux way to just use fork if you need parallelism back then? (I mean it's still a thing)

1

u/Usual_Office_1740 9d ago

I don't know. I’ve only been programming for a few years. I’ve used fork for capturing stdout write calls for unit testing but that was it.

1

u/ih-shah-may-ehl 7d ago

My big problem with fork is that it requires you to build everything into the same process, then fork, and choose behavior depending on which of the instances you are. In many cases, you want multithreaded parallelism in the same process

16

u/Eearslya 10d ago

That's the fun part, we already do have std::bitset.

9

u/setibeings 10d ago

alright, then we need to replace vector with a type that doesn't randomly do something different when it holds bools in particular. lol.

2

u/danielcw189 10d ago

and also give it a name that isn't misleading like "vector"

7

u/Ayjayz 10d ago

It's fixed size though

7

u/Beginning-Junket8979 10d ago

There is a std::bitset but it's more like a std::array<bit, N> in terms of storage allocation and has no iterators.

9

u/Usual_Office_1740 10d ago

In C++ a bool is actually 8 bits with the least or most significant bit set, depending on architecture. That's the smallest addressable unit available without extra bitwise operations.

7

u/bwmat 10d ago

Akshually, it has a sizeof of 1, and that could contain a different number of bits, at least prior to one of the newer standard versions

Lol cpp

3

u/Usual_Office_1740 10d ago edited 10d ago

That is what sizeof(bool) outputs. That 1 byte is based on the CHAR_BIT macro which the standard requires is atleast 8 bits. It could also be as much as 32 bits, apparently. Silly C++

4

u/the_horse_gamer 10d ago

this comes from C, which was created at a time where there were processors that used non-8 bit bytes.

there still exist such processors today, used in some niche places.

2

u/KellerKindAs 9d ago

That's the C remnant from a time, where a processor word was not guaranteed to be 8-bit (aligned). Also: CHAR_BIT is atleast 7 bit as a char is required to fit the ASCII table. The 8'th bit is already optional (but guaranteed on all modern systems with 8-bit aligned memory and 32/64 bit cpu words)

0

u/JanB1 10d ago edited 10d ago

Perfectly compilable code in C++23:

bool test1 = true;

int* test2 = reinterpret_cast<int*>(&test1);
*test2 = 5;

std::printf("%d", test1); // Prints "5"

2

u/KuntaStillSingle 10d ago

-1

u/JanB1 10d ago

Okay, not valid because somewhere it's written that "this is undefined behaviour", but compilable, and it does what I wrote. Well, depending on which compiler you use, with some you get an output of 1, with others you get an output of 5. But that's kinda my point.

→ More replies (5)

3

u/da_Aresinger 10d ago

it's called a vector. vectors are sequences of separate elements.

Elements have addresses. Every other vector has elements which can be addressed independently.

Bits cannot be addressed independently.

4

u/the_horse_gamer 10d ago

vectors are sequences of separate elements

well, no they're not. the C++ name was a mistake.

1

u/da_Aresinger 10d ago

I mean, cppreference literally says:

The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.

I guess that's not the ISO, but I'm not about to pull that out.

3

u/the_horse_gamer 10d ago

vectors are elements of vector spaces, not a sequence of numbers

std::vector is not a vector

1

u/da_Aresinger 10d ago

ok, I get your drift. You have a point.

3

u/the_horse_gamer 10d ago

Quote from the book "From Mathematics to Generic Programming" by Alexander Stepanov (the creator of the stl) and Daniel Rose:

The name vector in STL was taken from the earlier programming languages Scheme and Common Lisp. Unfortunately, this was inconsistent with the much older meaning of the term in mathematics and violates Rule 3; this data structure should have been called array. Sadly, if you make a mistake and violate these principles, the result might stay around for a long time.

0

u/[deleted] 10d ago

[deleted] — view deleted comment

1

u/the_horse_gamer 10d ago

vector<bool> may be specialised to store the bools packed into some larger data type

175

u/ImpulsiveBloop 10d ago edited 10d ago

typedef uint8_t bool8;

std::vector<bool8> booleansAsBytes;

Or just use it directly

std::vector<uint8_t> fuckBools;

61

u/dedservice 10d ago

Yes until you have std::vector<T> in a templated piece of library code and you try to do anything remotely complicated with it.

15

u/ImpulsiveBloop 10d ago

It's all use-case, I suppose. Larger programs can afford more refined solutions.

To say using uint8_t as a bool is bad because it can break when making templates is to say wood beams are bad because they will buckle under a skyscraper.

2

u/PastaPuttanesca42 9d ago

It's not that uint8_t breaks vectors, it's that users of the template that don't know it uses a vector internally will use bool instead.

1

u/4xe1 6d ago

Wouldn't they get a compiler error doing so?

1

u/PastaPuttanesca42 5d ago

I'm not completely sure that in some cases there wouldn't be undefined behaviour, but even if it fails to compile the error will likely be horrible and not easily understandable.

1

u/dedservice 5d ago

Using uint_8 isn't bad, but rather it's not an option as a replacement if you're the one writing the templated code. Partually because you don't know that bool was actually the intent when you get given a uint_8, but more importantly because in every single function that templates on T and uses vector<T>, you have to write a distinct version of the function that special-cases vector<bool> in case your users instantiate the template with a bool, which should be very reasonable and users should want to do by default, because bools are a useful datatype.

1

u/ImpulsiveBloop 5d ago

Hence why I said, "larger programs can afford mor refined solutions"... :/

I only mean that uint8_t is not bad for smaller programs because it does what it needs and is unlikely to cause any complications.

6

u/That-Cpp-Girl 10d ago

template <typename T>

class CoolerVector : public std::vector<T> { using std::vector<T>::vector; };

template <>

class CoolerVector<bool> : public std::vector<uint8_t> { using std::vector<uint8_t>::vector; };

1

u/dedservice 5d ago

Yeah I know there are workarounds but there just shouldn't have to be.

6

u/TheDreadedAndy 10d ago

I mean, as long as you know its a problem you can just use std::enable_if_t to block putting bools in your template. Or you can specialize your template to redirect bools to a more sensible type.

It's a fun landmine for those who don't know, though. But C++ is full of those.

14

u/dedservice 10d ago

Yes but it's silly. We could update the language past the footguns from 1989. 

3

u/StaticCoder 10d ago

Surely you mean requires

1

u/4xe1 6d ago

Isn't that the other way around? I'd expect std::vector<uint8_t> to play a lot nicer with templates than std::vector<bool>

1

u/dedservice 6d ago

Yes exactly. But if you're writing template code and don't know who's going to call it, you have to create specific carve-outs or overloads for vector<bool>, where if the designers had just let that be normal, you wouldn't need that special-case handling.

66

u/gazorpazorpazorpazor 7d ago

"I wish this booleans required 8x more resources"

-5

u/DM_ME_FROG_MEMES 6d ago

How many booleans are you using that that'll ever be an issue

14

u/moonlitpawprints 5d ago

Covers the ears of aging embedded systems

60

u/tickle-fickle 10d ago

That pisses me off so much, why not call it an std::bit_vector, why a different behavior for this one template type

25

u/AL_O0 10d ago

funnily enough there absolutely is already std::bitset

and I have absolutely no idea how it's different

18

u/tiajuanat 10d ago

Bitset is fixed size. Vector<bool> is dynamic, does not allow concurrent access and does not guarantee continuity of values in memory.

Vector<bool> was meant to be an example template specialization, which is why it's so funky.

1

u/AL_O0 10d ago

thank you, that does make more sense

5

u/gigayoink 10d ago

I see how slick and natural it would have been, but it just doesn't work out that way in practice

143

u/geekosas 10d ago

Why waste 7 bits?

30

u/PastaPuttanesca42 9d ago

Because when I write a function template

foo<T>

that internally does

std::vector<T> bar;
[stuff happens]
T* ptr = &bar[7]

foo<bool> is broken.

-18

u/geekosas 9d ago

Man Up

17

u/PastaPuttanesca42 9d ago

What kind of response is that? Do you actually have anything to say?

26

u/SchighSchagh 10d ago

Right? And you can always use uint8_t if you have an actual reason.

65

u/Still_Bit_7527 10d ago

Because i asked for a vector of bool, not vector of bits

26

u/geekosas 10d ago

This is the kind of guy that programed Google Chrome XD

15

u/Rainmaker526 10d ago

Then ask for a vector of bytes.

28

u/Still_Bit_7527 10d ago

Bool is a byte. At minimum. All types are min 1 byte, by standard. And sizeof returns integers. Please stop arguing and just accept a common issue. Dont be a contrarian

3

u/geekosas 10d ago

Look a python developer 

13

u/Still_Bit_7527 10d ago

Java*. Compiler can optimize how it wants but documentation and consistency comes first

0

u/[deleted] 10d ago

[removed] — view removed comment

10

u/_killer1869_ 10d ago

A bool, by definition, in just about any language there is, always takes up the amount of space of the lowest addressable memory unit, which is 8 Bit (excluding some special, outdated architectures where you can access single bits directly). C++ is the only language I know of where a data type using bool uses single bits for storing them. Is it more efficient? Yes. But it breaks the universally accepted standard. Consistency is far more important than minimal efficiency improvements. Just add a seperate data type for when you really need that efficiency into the standard library.

5

u/Still_Bit_7527 9d ago

It's even worse. C++ itself actually uses a whole byte for bools. It's only vector that uses bits to optimize when it's a vector of bools

→ More replies (1)

69

u/0xbenedikt 10d ago

I think the behavior of it is quite logical. Bits are supposed to be one bit in size. If you have them in isolation, they will have to expand to at least 8 bits, but once they are a vector, you give permission to the compiler to pack and optimize them. If you can't have them optimized, use a type that guarantees an individual address, if that is what you need

41

u/the_horse_gamer 10d ago

you give permission to the compiler

this is library level behavior, not a compiler optimisation

it breaks many invariants

the correct solution would have been to make std::dynamic_bitset

7

u/Thrawn89 10d ago

Maybe optimize the memory footprint, but if it packs them, then the underlying memory hardware wont be able to just write to them directly.

All of a sudden you double your access bandwidth on writes since they may be promoted to read-modify-writes.

3

u/0xbenedikt 10d ago

It depends a lot on what platform the software runs on. C++ runs on everything from 8-bit microcontrollers to high performance compute platforms. On a microcontroller there often is an instruction that modifies a bit in a single cycle, while it is more costly on other platforms

2

u/narrill 10d ago

I think the behavior of it is quite logical. Bits are supposed to be one bit in size.

A bool in C++ isn't a bit.

4

u/0xbenedikt 10d ago

Yes and no. A bool variable is 8 bits, since by specification it needs its own address. But the information encoded in one bool is supposed to be one bit

3

u/narrill 9d ago

The information encoded doesn't matter; within C++'s type system, a bool is not a bit. Meaning, vector<bool> does not actually hold any bools, and any code that attempts to interact generically with a vector that happens to be a vector<bool> may be subtly broken.

Threading is the most obvious culprit here. For any other element type it's safe for different threads to read and write to different elements of the vector. For vector<bool> it isn't, because its elements are always read and written to in groups of eight.

33

u/UnhappyJudge2487 10d ago

But bools as a standard are stored as bytes not bits. If you initiate a bool in cpp it's stored in a byte so it can be addressed

29

u/unknown_alt_acc 10d ago

std::vector<bool> may be specialized to store bools compactly and non-contiguously. It is the only initialization of std::vector for which this is allowed, but it is not guaranteed by the standard.

1

u/UnhappyJudge2487 10d ago

So the problem is that it could be done as but but wasn't?

35

u/unknown_alt_acc 10d ago

No, the problem is that the standard allows it at all.

All other instantiations of std::vector are guaranteed to store addressable objects contiguously. std::vector<bool> is arbitrarily allowed to break this guarantee. This can break generic code if you don't defensively program around it, which defeats the whole point of having a strong type system with robust generic programming facilities.

What really should have happened is simply using the type system for its purpose. std::vector<bool> should not have been specialized, and a separate container named something like std::dynamic_bitset should have been introduced to cover the cases where you do want to store compacted boolean values. This way,std::vector maintains a consistent contract and the type system gets used to better express the programmer's intent.

4

u/ivain 10d ago

Great explanation.

-5

u/nimrag_is_coming 10d ago

Sort of, the compiler is allowed to pack sequential book fields in classes into single bytes

10

u/unknown_alt_acc 10d ago

The compiler is absolutely not allowed to pack contiguous bools. That breaks the addressability requirement of objects. If you want packed Boolean values, the language gives you plenty of ways to express that.

23

u/Immediate_Form7831 10d ago

Thank you for reminding me that C++ is an insane mess.

32

u/Luzzgar 10d ago edited 10d ago

Yet another example of C++ doing something in a weird and not obvious way.

Making a deep knowledge if its inner workings mandatory to use it correctly, which is the antithesis of a good programming language.

That's the kind of crucial details that should be communicated to the user directly.

8

u/Ahmouse 10d ago

It's only weird if you assume their intention is to make it easy and intuitive to use. Maybe the goal was job security for the experts that learn it.

2

u/nicuramar 10d ago

As long as you only use it in an “STL way”, you don’t really need to know of its inner workings.

12

u/TatharNuar 9d ago

I'd rather have my bools packed, since I generally work with microcontrollers and need every byte I can save. For some reason, the compiler that comes with Arduino IDE tried to store my hundreds of bools bytewise and ran out of memory, and I had to make a struct to get them to pack the way I wanted. Also, packed bools can be set or unset together in a single operation, so it can be a lot faster.

8

u/royavidan 9d ago

But if that's what you want, why not just use std::bitset? Why does it have to be the default boolean vector type when it's worse most of the time?

1

u/TatharNuar 8d ago

I don't know the reasoning why it would ever be worse, but maybe I'm assuming some abstraction you aren't using.

3

u/fweaks 8d ago

If you are setting or reading a single bit, it is usually less performant because it requires more operations.

Also it can no longer be pointer iterated the same as any other vector could be, breaking templating code. You have to keep making special case code just for it.

And thats if you even know about it, since it's not clear just looking at the type that its completely different from every other specialization of its template.

1

u/TatharNuar 8d ago

Bitwise logic operations are supposed to be the fastest operations a CPU can run, though. Ideally you want to group up bits you're likely to read together into the same word so a single instruction reads all of them. Same goes for setting bits using a bitmask. You can still pointer iterate, but you're doing it per-word rather than per-bool. You'd get a speedup equal to the word size because you're effectively parallelizing your writes with a single bitwise logic instruction.

I personally tend to use C more than C++, and HDLs even more than that, but my first impression of bool was that it was meant to be a single bit in size so you could do things like that.

1

u/SirBackrooms 7d ago

This seems like a special case that would benefit from its own type like bitset rather than having vectors arbitrarily work differently for a single type and break stuff unless you know to take care of it.

1

u/Firm-Can4526 6d ago

But normally in microcontrollers you are not using the standard library....

17

u/Mountain-Ox 10d ago

What's the problem with this? I've seen a lot of people so bitwise operator stuff as an optimization. What is wrong with being able to address the bits directly for any length?

20

u/wallstop-dev 10d ago edited 10d ago

It is the only vector type that doesn't return a mutable reference (among other things), so if you're using it in some core abstraction and later on someone wants to use that abstraction with bool types, that code either behaves incorrectly (potentially silently) or doesn't compile.

I ran into this exact scenario in my first job on the architecture team for a massive simulation. Working around it was incredibly annoying.

Edit: That is just my personal experience - the problem, in general, is that it breaks the API/contract/expectations of vector.

The full list (to my knowledge):

  • No pointers or contiguous layout
  • As part of the above, it is incompatible with std::span
  • No .data() function (????)
  • Broken range-based for loops (for(auto& b : vec)) doesn't compile
  • Not thread safe. If you have a (normal) vector where you assign a thread to each populated index, it is thread safe (single-owner). In vector<bool>, a single index shares its underlying data with other indices, so this breaks

Uber point: It's a giant foot gun edge case.

2

u/amshegarh 10d ago

why the hell would you want an array of bools? like intention wise, curious

10

u/wallstop-dev 10d ago edited 10d ago

I think you maybe missed my point. It's that building an abstraction with a foundation of vector that leaks some of its core contracts, like mutable reference based indexing and contiguous data type access, will end up breaking and biting you in unexpected ways. It's also that it breaks the (general) API contract of vector.

The question is more "why *wouldn't I* want this core, generic primitive to adhere to its API contract regardless of the type that I put into it?"

If you look at raw vector and ask "why do I want an array of bools", yea sure, whatever, use a literal array of bools or a bit set or this thing or that thing or who cares.

But as you start zooming out and building stuff around the *concepts* of vectors and arbitrary types, eventually you end up with, say, like, a Vehicle class, built on that abstraction. And then you go to build a vehicle that uses bools in a certain way, for business reasons, and suddenly your code doesn't compile. They didn't necessarily want a literal array of books - they just wanted to use your thing that says "you can use me with any generic type" except WOOPS not bools and only not-bools, for some reason.

-1

u/amshegarh 10d ago

I am specifically asking because i cannot recall ever using array of bools (in all of my used languages) over the 6+ years, except for my earliest years in my amateur code where i used array of bools + array of string (for example) vs array<struct=bool + str>

3

u/wallstop-dev 10d ago edited 10d ago

I gave examples in both of my comments for the real world use cases I encountered. Abstractions sitting at the basis of primitives that are used in a large (million+ LoC code base)

If you want a contrived explicit example of a literal array of bools, consider an array of coin flips, or any other data that can be thought of as a (ordered) sequence of truth or decision (yes/no) values.

2

u/Mountain-Ox 10d ago

The case I had at a previous job was we need to know if a retailer was available at a given time. We need to be able to check a lot of them very quickly. So we had a string of 1s and 0s, each one indicated a 15 minute segment of the week. That's too many bits to fit in an integer for a simple bitwise operator. I don't recall the implementation details anymore, but we the I/O for loading thousands of these strings for processing was kind of slow. It was PHP which didn't help.

2

u/autumnal-lights 9d ago edited 9d ago

? i mean isn't this perfect for bits tho? like

~ A & ~ B and then just like

a ~ custom u number_large_enough;

the scans are trivial tho :shrug:

and like workday perfectly fits into u64, and 3 u64's perfectly align with the 24 hours? like? that's perf?

1

u/amshegarh 10d ago

That is interesting, but you can directly use pg for that (assuming you had one?)

Otherwise its just an array of ints (instead of one) + bitwise logic

1

u/Mountain-Ox 10d ago

We were on MySQL, this was during the lamp stack days. And I don't know if MySQL ever added features like that. I don't think it had native json support.

1

u/autumnal-lights 9d ago

not sure why you're being downvoted, array is on the stack, it's the same as a class which packs like 3 ints?

1

u/LeDYoM 8d ago

My impression has always been that they wanted to have an example of class template specialization in the standard.

But probably I am wrong.

17

u/Own_Lake_276 10d ago

The problem is that it’s inconsistent and leads to unexpected bugs. If I want to use a bitmask because I really care about memory then I’ll use a bitmask

0

u/Mountain-Ox 10d ago

What kind of bugs? Nothing would be inspecting the memory values of the vector directly.

The problem with a bit mask is it can only work up to 64 bits afaik. What if you have hundreds of bools that you need to manage?

7

u/telionn 10d ago

Try grabbing a pointer-to-bool from std::vector<bool> and see what happens.

Vector<bool> isn't that bad in a vacuum, honestly, since you can just avoid it. The real problem is when you write `template<typename T> class MyDataStruct { std::vector<T> innerStorage }` and then create a `MyDataStruct<bool>` and it unexpectedly falls apart. Now you have to build a pointless type trait system to remap bool onto uint8_t or something.

4

u/narrill 10d ago

What if you have hundreds of bools that you need to manage?

Then you have a separate type that works the way vector<bool> does now, allowing vector<bool> to, you know, be a vector.

1

u/Bitter_Ad3906 9d ago

Problem of wrong implementation of bool, not for what use case for it. If you need separate implementation for it, then it should be excluded from start. Assume you have sequence of simple numbers and in that list got 12, 12 also number but wrong one. It’s same for std::vector<bool> differ from rest.

1

u/narrill 9d ago

I don't know what this comment is trying to say. Dynamic bool collections with and without bit packing are both legitimate use cases, and of the two, vector<bool> should obviously be the latter because that is how vector already works. If you want a tightly packed collection that breaks vector's invariants, it should be its own type and not a specialization of vector.

I'm not sure what "wrong implementation of bool" is meant to mean either. A bool in C++ is not a single bit, definitionally.

1

u/Bitter_Ad3906 7d ago

Just when implement class need follow rules to all, not make 1 out of rest. Mem usage be good, but for it can be new one like memCompactVector<bool> etc.

2

u/yota-code 10d ago

Adressing bits directly is nice but bool is a well known type by itself and has a size of 1 octet everywhere else... Seems inconsistent 

3

u/haitei 10d ago edited 9d ago

What is wrong with being able to address the bits directly for any length?

Nothing, that's an excellent feature for a dynamic bitset. But when I ask for a dynamic array of bools, I want a dynamic array of bools.

1

u/Carbon_Cotton 9d ago

Because std::vector<T> has interface all of its implementations must follow - stuff like iteration, dereference

And while storing booleans as bits in std::vector<bool> shrinks the space usage by nearly 90%, it also means it cannot fully implement the std:vector interface.

Good example is reference - in other vectors, you can take reference to one of its items. You can then use this reference to work with item directly.

auto vec = std::vector<int>();
vec.push_back(10);

// this will obtain reference to 0th item    
auto& val = vec[0];
val = 15;

// this will print '15'    
std::cout << vec[0] <<std::endl;

This is IMPOSSIBLE with std::vector<bool> because there are no bools inside to reference - and referencing bits is impossible as well.

Instead, it will return weird proxy object that is trying its best to pretend it is bool reference. But it cannot ddo everything - and that breaks interface

3

u/jolharg 10d ago

just use flag bytes lol

2

u/Megane_Senpai 10d ago

Yeah, like data padding isn't a thing lol.

4

u/Buyer_North 10d ago

people just hating because they dont understand cpp...not gonna say why, because you dont deserve it if you dont know it

25

u/Aurii_ 10d ago

You don't answer it because you yourself have no idea

6

u/-Ambriae- 10d ago

Please explain in what world is implicitly converting a vector<bool> to a bitset normal?

2

u/ih-shah-may-ehl 7d ago

There are plenty of things the CPP committee itself had brutal fights over and eventually stripped back out. Stop kissing ass.

2

u/Droggl 10d ago

Its not that people don't see why the bit vector implementation can be useful, but its really not unreasonable to see "vector<bool>" and expect the type to be a vector and store bools (it does neither though)

2

u/Sam260901 10d ago

For this to work u had to assume their wish servers store in c++

I'd have made first wish to change their language of storage of wishes to cpp, then on 2nd wish would've done this.

1

u/Banes_Addiction 10d ago

Sure. It totally seems like a worthwhile reason to make all pointers floating point.

1

u/stupled 10d ago

But is bool...

1

u/Successful-Active-21 10d ago

just wrap the bool and use vector<wrap<bool>>

1

u/Hot-Category2986 9d ago

*Internal screaming*
*Reread because maybe I misunderstood that*
Maybe I'm missing something about why someone would want to overcomplicate a bit...

1

u/QuietComputerDr 8d ago

I hope the genie also changed everyone's legacy code.

1

u/Infamous_Ticket9084 5d ago

Tbh at this point only solution for this problem would be disallowing it in linters and suggesting either deque or bitset depending of whether you want packing

1

u/MartinByde 5d ago

Wtf, why wouls you do that?

1

u/Ecstatic-Middle-9564 5d ago

vector<byte> or vector<uint8_t> C and C++ let you use pretty much anything as a boolean.

1

u/TerryHarris408 10d ago

Why would you want to bloat up your memory and waste 87% of your space? C++ fixed a mistake that the bool type introduced in C for simplicity of implementation. If you don't like vector bool for whatever reason then feel free to use vector uint8_t for the C style feeling

3

u/No-Information-2571 10d ago

You bloat up the memory in other ways, since bits can only be accessed through bit shifting and boolean operations, and then need to be copied into an int8 anyway. Even if you just want to branch, the CPU will do bit arithmetic. There's specific reasons for when you want to store bools as bits, and not as bytes. VERY SPECIFIC reasons. Like accessing data that is already stored as packed bits, like a register. Or when you are absolutely sure you need to pack bits for dense computations (think: chess engine).

That's why everyone here agrees that it should have been a std::bit_vector class, while std::vector<bool> should have been one byte per bool. It's a landmine in various ways. For example, it breaks all basic assumptions you have about such a vector, like sizeof(T) * n being the total size of the vector in memory.

1

u/Cheap-Chapter-5920 10d ago

This kind of stuff is popular in the embedded world though. Working with processors with 8K of program memory and 128 bytes of RAM and some of those processors have single bit instructions. It's one of the reasons I have to delve into assembly.

2

u/No-Information-2571 10d ago

Then you typically still lay a struct on top, and not an array.

But I know all about smart cards and densely packed formats, that's why I am mentioning "specific reasons". Chess engine is also a good example, 8x8 bits fit neatly into an uint64. Piece movement turns into bit shifts, checking legal moves is mostly AND and OR.

Otherwise, you're trading that 87% "dumb" memory for easily 5x the number of instructions, from a simple array lookup to bit arithmetic. "Small" isn't always good, especially on 64-bit architectures.

5

u/the_horse_gamer 10d ago

the problem is being implicit

vector<bool> breaks any remotely complex generic code

this optimisation should have been a separate type (tr2 had std::dynamic_bitset)

2

u/TerryHarris408 10d ago

what exactly does it break?

5

u/the_horse_gamer 10d ago edited 10d ago

a[0] is no longer a bool&, instead a custom type pretending to be a bool& via operator overloading

can't a.data()

can't iterate via auto&& you can, but it suffers from the same issues as the aforementioned a[0] thing

access to disjoint indices is not necessarily thread-safe

iterator may not be a LegacyForwardIterator, preventing use of many standard iterator-taking functions (with an error at compile time, or at runtime, or UB if you try)

and it's not even guaranteed to use this optimisation

3

u/Supadoplex 10d ago

can't iterate via auto&& 

I'm pretty sure you can. Did you mean auto&?

1

u/the_horse_gamer 10d ago

seems I remembered incorrectly. will fix.

0

u/yjlom 10d ago

Vector<bool> taking 1 bit per element is sensible. What isn't is bool * only being precise to the byte (well it did make sense back in the 70s when memory was as fast as cpus but now the time required to perform a shift and mask is negligeable compared to the time saved from improving cache locality).

9

u/unknown_alt_acc 10d ago

All objects in C++ must be addressable. Bits are not addressable, and therefore cannot constitute a full object.

And, being C++, you are given several ways to pack boolean values if you need to. You can do the classic bit flags yourself, or use a std::bitset, or you can use a bit field if you want to explicitly name your flags. So ultimately, I think that it's worth bool being a full byte just for consistency with all other data types, and anything sub-byte being an explicit opt-in.

→ More replies (4)

-7

u/Kadabrium 10d ago

I wish java had one single array type that is resizeable (takes literally 1 line of code in a gc language) rather than array, arraylist, tolist, aslist, listof, the list of list goes on listing

27

u/willow-kitty 10d ago

You..do realize that arrays and lists are different things, right? Like not just in Java.

3

u/suvlub 10d ago

Javascript begs to differ.

Python calls them "list", but also has only 1 type, which is what I think is the important part, not whether they are called "arrays". (and no, the arrays module doesn't count, that's a specialized library type, not comparable to the duality you have to deal with when using Java)

0

u/_PM_ME_PANGOLINS_ 10d ago

All you're doing is showing you don't know how to use neither Java nor Python properly, or haven't touched either since the early 00s.

-5

u/Kadabrium 10d ago

If your point is linked lists, lumping them with arrays is a mistake that breaks code in itself and linked lists are next to useless anyway. None of the lists i mentioned even is a linked list. They are all array types that are mutually incompatible for some bool reason.

7

u/plz-no-b4n 10d ago

A list is an abstract type. A linked list is a concrete implementation of a list.

→ More replies (2)

6

u/willow-kitty 10d ago

It is not, no. My point is that the theoretical definition is different.

Arrays are defined as randomly-addressable blocks of data where each element is the same width. They're pretty low-level and not resizable generally (though some implementations allow that by making a copy.)

While lists retain some characteristics of arrays (like being ordered and allowing random access, though time complexity depends on the underlying implementation) but allow items to be added, removed, and reordered. You know, like a to-do list.

Lists are often wrappers around arrays, sure, which allows for fast random access at the cost of some operations (like add/remove/reorder) being costlier, while a linked list can do fast add/remove/reorder and sequential access while random access is more expensive, but at the end of the day, those are list operations, not array operations (even if some languages give arrays some of those capabilities.)

To throw in another one: bags don't preserve order and therefore don't support reordering but do support fast adding and removing. You know, like the items in a bag. That might be backed by an array too, but it's not an array or a list either. The contract is different.

-1

u/Kadabrium 10d ago

Many of the java list types i mentioned also don't even support resizing, so your arg on that is moot

5

u/_PM_ME_PANGOLINS_ 10d ago

You only mentiond one list type. The other words in your list are methods.

→ More replies (1)

3

u/gigayoink 10d ago

linked lists are next to useless anyway

Linked lists are super common and extremely useful. Just not as a list ADT.

As a List they're absolute trash, but there are so many linked lists that people don't think of as linked lists. Java's BufferedInputStream .flush() is textbook linked list traversal.

3

u/FlySafeLoL 10d ago

An array is packed in memory, resizing it naive way means allocating more memory at the tail. And who guarantees that there is free memory up there?

So, you either redefine array (lame), or copy it elsewhere on resize (expensive, but that's what various collections actually do under the hood), or just use another collection which doesn't require to be packed all in one place (at the cost of performance of iterating over it).

0

u/Kadabrium 10d ago

No list should sacrifice array compatibility for linked list compatibility ever. And then with java as i said the issue isnt just linked lists, but that there are multiple incompatible array based list types. And no, many of them don't allow resizing, if thats what you think is the essence of a list.

0

u/NegZer0 10d ago

But bool is not a byte in C++ either, it’s implementation specific and sizeof(bool) is not required to be 1. 

If you want a vector of bytes use vector<unsigned char> 

1

u/narrill 10d ago

A bool is also not a bit in C++, and sizeof(bool) can never return one bit because a single bit isn't addressable.

1

u/NegZer0 10d ago edited 10d ago

Yes, but the standard does not provide a size, deliberately to allow for implementation specific specializations like this.

If you need individually addressed bytes that can be zero or non zero, there are easy ways to do that, this is making a big deal over nothing (also the bit wise versions have actual uses)

EDIT: Also the standard type is using a bit to define boolean (0 or 1) it's just that the smallest addressable value is a byte, so they have to stuff it into a byte.

1

u/narrill 9d ago

This has absolutely nothing to do with the standard not specifying a concrete size. What is stored in a vector<bool> is not bool, flat out. So its size is irrelevant.

Bitwise bool collections do indeed have legitimate use cases, which is why they should have been included in the standard as their own independent type. Including them as a goofy specialization of vector<bool> causes very real problems with template metaprogramming and thread safety.

0

u/StCreed 10d ago

Seems like people don't understand bits and boolean. If you don't understand it, just use a byte-vector.