Begin after vectors and views and
iterator categories. Most vector
Save a bool value when the result must be a snapshot
A mutable vectorauto retains access to its bit; converting it to bool reads a value now.
The implementation may pack bits into machine words, but code must not depend
on word size, exact storage layout or the size of the proxy object.
#include <vector>
#include <cstdio>
int main() {
std::vector<bool> flags{true};auto proxy=flags[0];bool snapshot=flags[0];
flags[0]=false;
std::printf("proxy %d, snapshot %d\n",int(bool(proxy)),int(snapshot));
}auto is not inherently wrong: range-for auto bit can deliberately copy a
proxy and still modify its original bit. auto&& is another useful generic
binding. auto& cannot bind to a temporary proxy on the implementations used
here. With an ordinary vector
There is no contiguous bool array to borrow
Neither vector
A retained proxy can dangle after reallocation or erasure just like any other borrowed access object. A bool snapshot stays a bool. Simultaneous writes to different packed bits may still touch the same underlying memory location; do not assume separate indices make parallel writes race-free.
bitset expresses fixed-width bit operations
bitsetcount, test, set/reset, AND/OR/XOR and shifts without narrowing to an
integer. to_ullong() can throw when high set bits do not fit.
Bitset shifts discard shifted-out bits; shifting by N or more yields all zero
bits. This differs from shifting a built-in integer by its width, which violates
that operator's precondition. The mutable bitset subscript is also a proxy;
test(index) is a checked read, whereas subscript has its own bounds contract.
#include <bitset>
#include <cstdio>
int main() {
std::bitset<128> sums;sums.set(0);
for(unsigned weight:{1U,3U,3U})sums|=sums<<weight;
for(unsigned i=0;i<sums.size();++i)if(sums.test(i))std::printf("%u ",i);
std::puts("");
}The build deliberately includes high bits 64 and 127, empty vectors, adjacent word boundaries and shifts larger than the entire bitset. A solution that only works for one machine word, returns a live proxy or accidentally turns the subset calculation into an unbounded knapsack does not satisfy its contract.