Reputation:
The vector<bool>
class in the C++ STL is optimized for memory to allocate one bit per bool
stored, rather than one byte. Every time I output sizeof(x)
for vector<bool> x
, the result is 40 bytes creating the vector structure. sizeof(x.at(0))
always returns 16 bytes, which must be the allocated memory for many bool
values, not just the one at position zero. How many elements do the 16 bytes cover? 128 exactly? What if my vector has more or less elements?
I would like to measure the size of the vector and all of its contents. How would I do that accurately? Is there a C++ library available for viewing allocated memory per variable?
Upvotes: 4
Views: 2841
Reputation: 385274
I don't think there's any standard way to do this. The only information a vector<bool>
implementation gives you about how it works is the reference
member type, but there's no reason to assume that this has any congruence with how the data are actually stored internally; it's just that you get a reference
back when you dereference an iterator into the container.
So you've got the size of the container itself, and that's fine, but to get the amount of memory taken up by the data, you're going to have to inspect your implementation's standard library source code and derive a solution from that. Though, honestly, this seems like a strange thing to want in the first place.
Actually, using vector<bool>
is kind of a strange thing to want in the first place. All of the above is essentially why its use is frowned upon nowadays: it's almost entirely incompatible with conventions set by other standard containers… or even those set by other vector
specialisations.
Upvotes: 4