For older (pre-C++11) compilers, use parenthesis (return wstring(...)
) instead of braces (return wstring{...}
), and also use std::vector::operator[]
to access the allocated array, not std::vector::data()
(which didn’t exist yet), eg:
return wstring(
&Buffer[0], MultiByteToWideChar(CP_UTF8, 0, Str.c_str(), -1, &Buffer[0], wcharCount)
);
That being said, the source std::string
’s size is the wrong size to use for the std::vector
. Call MultiByteToWideChar()
twice - call it once with a NULL output buffer to calculate the necessary size, and then call it again to write to the buffer. And, you should be using the std::string
’s actual size instead of -1 for the source buffer size.
wstring widen(const string &Str) {
const int wcharCount = MultiByteToWideChar(CP_UTF8, 0, Str.c_str(), Str.size(), NULL, 0);
vector<wchar_t> Buffer(wcharCount);
return wstring(
&Buffer[0], MultiByteToWideChar(CP_UTF8, 0, Str.c_str(), Str.size(), &Buffer[0], wcharCount)
);
}
Note that in C++11 and later, it is safe to use a pre-sized std::wstring
directly as the destination buffer, you don’t need the std::vector
at all, because std::wstring
is guaranteed to use a single contiguous block of memory for its character data. And even in earlier compilers, this is usually safe in practice (though NOT guaranteed) because most implementations use a contiguous block anyway for efficiency:
wstring widen(const string &Str) {
const int wcharCount = MultiByteToWideChar(CP_UTF8, 0, Str.c_str(), Str.size(), NULL, 0);
wstring Buffer;
if (wcharCount > 0) {
Buffer.resize(wcharCount);
MultiByteToWideChar(CP_UTF8, 0, Str.c_str(), Str.size(), &Buffer[0]/* or Buffer.data() in C++17 */, wcharCount);
}
return Buffer;
}