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

小太郎 picture 小太郎 · Jun 4, 2011 · Viewed 31.3k times · Source

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?

Answer

Lukáš Lalinský picture Lukáš Lalinský · Jun 4, 2011

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.