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
?
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.
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);
std::string::size()
is indeed the size in bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With