Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get size of a std::string's string in bytes

I would like to get the bytes a std::string's string occupies in memory, not the number of characters. The string contains a multibyte string. Would std::string::size() do this for me?

EDIT: Also, does size() also include the terminating NULL?

like image 691
小太郎 Avatar asked Jun 04 '11 08:06

小太郎


3 Answers

std::string operates on bytes, not on Unicode characters, so std::string::size() will indeed return the size of the data in bytes (without the overhead that std::string needs to store the data, of course).

No, std::string stores only the data you tell it to store (it does not need the trailing NULL character). So it will not be included in the size, unless you explicitly create a string with a trailing NULL character.

like image 143
Lukáš Lalinský Avatar answered Oct 09 '22 12:10

Lukáš Lalinský


You could be pedantic about it:

std::string x("X");  std::cout << x.size() * sizeof(std::string::value_type); 

But std::string::value_type is char and sizeof(char) is defined as 1.

This only becomes important if you typedef the string type (because it may change in the future or because of compiler options).

// Some header file: typedef   std::basic_string<T_CHAR>  T_string;  // Source a million miles away T_string   x("X");  std::cout << x.size() * sizeof(T_string::value_type); 
like image 45
Martin York Avatar answered Oct 09 '22 11:10

Martin York


std::string::size() is indeed the size in bytes.

like image 40
Will A Avatar answered Oct 09 '22 11:10

Will A