[Solved] How sizeof(std::cout) is 140 whereas sizeof(std::string) is only 4? [closed]


Basically it comes down to the fact that an iostream has quite a bit of state to store, but a string has very little.

Nonetheless, the idea of a string having a size of only 4 is a little surprising (at least to me). I’d normally expect something like 12 for a 32-bit implementation, or 24 for a 64-bit version.

In particular, a string will typically contain three things: a pointer to the actual buffer to hold the data (typically allocated on the free store), a size_t to contain the size of that buffer, and a size_t to contain the number of characters currently being stored. In a typical case, each of those will be 32-bits on a 32-bit implementation and 64-bits on a 64-bit implementation.

It’s entirely possible to justify a string object that’s somewhat larger than that as well–for example, it’s fairly common to store the data for a small string directly in the string object itself (“short string optimization”). In this case, you might have space for (up to) something like 20 characters in the string object itself, which will typically increase its size still further.

4

solved How sizeof(std::cout) is 140 whereas sizeof(std::string) is only 4? [closed]