There is inherent conflict in the question as written: std::string
is defined as std::basic_string<char,...>
-- that is, its element type is char
(1-byte), but later you stated "the string contains a multibyte string" ("multibyte" == wchar_t
?).
The size()
member function does not count a trailing null. It's value represents the number of characters (not bytes).
Assuming you intended to say your multibyte string is std::wstring
(alias for std::basic_string<wchar_t,...>
), the memory footprint for the std::wstring
's characters, including the null-terminator is:
std::wstring myString;
...
size_t bytesCount = (myString.size() + 1) * sizeof(wchar_t);
It's instructive to consider how one would write a reusable template function that would work for ANY potential instantiation of std::basic_string<> like this**:
// Return number of bytes occupied by null-terminated inString.c_str().
template <typename _Elem>
inline size_t stringBytes(const std::basic_string<typename _Elem>& inString, bool bCountNull)
{
return (inString.size() + (bCountNull ? 1 : 0)) * sizeof(_Elem);
}
** For simplicity, ignores the traits and allocator types rarely specified explicitly for std::basic_string<>
(they have defaults).