Jump to content
  • Advertisement
Sign in to follow this  
neverland

std::string size

This topic is 4820 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!