I want to calculate how much memory is allocated when I create and assign values to a string.
string s = "";
cout << sizeof(s) << endl;
cout << sizeof(s.at(0)) * s.capacity() << endl;
s = "1234567890qwertz";
cout << sizeof(s) << endl;
cout << sizeof(s.at(0)) * s.capacity() << endl;
Is this all memory that my string s consumes? The initial/static part that I get by simply calling sizeof(s) (being 40 bytes on my machine) plus the dynamic part - the size of one character times the allocated placeholders for making strings efficiently resizable (on my machine the string s first allocated a block of 15 bytes until the point where the text is too long, so after the second assignment the dynamic part is 31 bytes). Why not 16 and 32 bytes by the way?
Is this way of thinking about it (static + dynamic for each string is all the memory it occupies) correct?
Meaning that if I have a std::vector of strings, and I wanted to calculate all the memory for that vector as well, I would need to kind of do the same thing: I add the initial/static size of my vector to get the plus the dynamic part which means the total memory occupied by one string the way I do it above for each string inside the vector?
vector<string> cache;
// fill cache with strings of dynamic length
int size = sizeof(cache);
for (int i = 0; i < cache.size(); i++)
{
size += sizeof(cache[i]);
size += sizeof(cache[i].at(0)) * cache[i].capacity();
}
So to sum it all up, is that the correct amount of memory occupied by my "cache"?
Edit: Or do I also need to take into account that a std::vector itself also has a .capacity() >= .size() which could mean that I would actually need to do this:
for each cache.capacity()
- I would need to add sizeof(cache[i])
and additionally
for each cache.size()
- add sizeof(cache[i].at(0)) * cache[i].capacity()
??