Josh Josh - 4 months ago 56
C++ Question

Is this code safe using wstring with MultiByteToWideChar?


the way I am with

std::wstring widen(const std::string &in)
int len = MultiByteToWideChar(CP_UTF8, 0, &in[0], -1, NULL, 0);
std::wstring out(len, 0);
MultiByteToWideChar(CP_UTF8, 0, &in[0], -1, &out[0], len);
return out;


If you're asking will it work, probably. Is it correct?

  1. You should use in.c_str() instead of &in[0]
  2. You should check the return value of MultiByteToWideChar at least the first time.
  3. MultiByteToWideChar invoked with a (-1) length, if successful, will include accounting for a zero-terminator (i.e. it will always return >= 1 on success). The length-constructor for std::wstring does not require this. std::wstring(5,0) will allocate space for six wide-chars; 5+zero-term. So technically you're allocating one-too-many wide-chars.

From MultiByteToWideChar docs on cbMultiByte and -1:

If this parameter is -1, the function processes the entire input string, including the terminating null character. Therefore, the resulting Unicode string has a terminating null character, and the length returned by the function includes this character.