std::string size

Started by
4 comments, last by MaulingMonkey 18 years, 6 months ago
std::string str; cout << sizeof(str) << endl; I'm reading a book said that std::string object size is 8. But on gcc the output is 4, on VC the output is 28. I am confused.
Advertisement
sizeof(std::string) is dependent on the compiler and version of the standard library it uses. There is no standard size for it.
As SiCrane said, use std::string::size() when measuring a string:

std::string s( "12345" );
std::cout << s.size() << std::endl;
:stylin: "Make games, not war.""...if you're doing this to learn then just study a modern C++ compiler's implementation." -snk_kid
Did it really say that? If so, consider throwing your book away. Bad information is worse than ignorance. Maybe your book didn't say that though, maybe it said that in a specific implementation sizeof(string) is 8. Either way it is very rare that you would actually want to know the exact size of your data, especially of a nonprimative type. Most of the time that you see sizeof you see a potential bug.
Quote:Original post by Glak
Most of the time that you see sizeof you see a potential bug.


I don't know about that claim.
Quote:Original post by Anonymous Poster
Quote:Original post by Glak
Most of the time that you see sizeof you see a potential bug.


I don't know about that claim.


I do :-p. Then again, I'm biased, I have a little function called industry::size_of in my personal library. It returns the number of elements in an array or container, and fails to compile with pointers or plain values.

That is, starting with this:

int data[ 100 ] = { 31 , 24 , 0 };

I prefer this:

assert( industry::size_of( data ) == 100 );

To this:

assert( sizeof( data ) / sizeof( data[0] ) == 100 );

Ironically, the first one is shorter to type out even when I fully qualify it.

Also, I'm with Glak. The size of std::string is implementation-dependant. VC mantains a small buffer so that it dosn't have to dynamically allocate small strings. GCC may be using some sort of copy-on-write mechanism if it's a recent version.

This topic is closed to new replies.

Advertisement