Sign in to follow this  
neverland

std::string size

Recommended Posts

neverland    145
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.

Share this post


Link to post
Share on other sites
SiCrane    11839
sizeof(std::string) is dependent on the compiler and version of the standard library it uses. There is no standard size for it.

Share this post


Link to post
Share on other sites
stylin    758
As SiCrane said, use std::string::size() when measuring a string:

std::string s( "12345" );
std::cout << s.size() << std::endl;

Share this post


Link to post
Share on other sites
Glak    315
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest 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.

Share this post


Link to post
Share on other sites
MaulingMonkey    1730
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this