c++ - How sizeof(std::cout) is 140 whereas sizeof(std::string) is only 4? -


consider following program:

#include <iostream> int main() {     std::cout<<sizeof(std::string)<<'\n';     std::cout<<sizeof(std::ostream)<<'\n';     std::cout<<sizeof(std::istream)<<'\n';     std::cout<<sizeof(std::cout); } 

the output on compiler(g++ 4.8.1)

4  140  144  140 

the output confuses me. why sizeof string class 4 bytes & ostream & istream gives 140 & 144 bytes respectively? sizeof(std::cout)is 140 bytes same sizeof(std::ostream). so, think because cout object of type ostream that's why getting output same here. right? these sizes compiler dependent?

basically comes down fact iostream has quite bit of state store, string has little.

nonetheless, idea of string having size of 4 little surprising (at least me). i'd expect 12 32-bit implementation, or 24 64-bit version.

in particular, string typically contain 3 things: pointer actual buffer hold data (typically allocated on free store), size_t contain size of buffer, , size_t contain number of characters being stored. in typical case, each of 32-bits on 32-bit implementation , 64-bits on 64-bit implementation.

it's entirely possible justify string object that's larger well--for example, it's common store data small string directly in string object ("short string optimization"). in case, might have space (up to) 20 characters in string object itself, typically increase size still further.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -