gpt4 book ai didi

c++ - 这段代码将 wstring 与 MultiByteToWideChar 结合使用是否安全?

转载 作者:搜寻专家 更新时间:2023-10-31 00:40:45 25 4
gpt4 key购买 nike

使用 std::wstring 就像我使用 MultiByteToWideChar 一样?

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;
}

最佳答案

如果您问它是否有效,可能是。这是对的吗?

  1. 您应该使用 in.c_str() 而不是 &in[0]
  2. 您应该至少在第一次检查 MultiByteToWideChar 的返回值。
  3. MultiByteToWideChar 以 (-1) 长度调用,如果成功,将包括占零终止符(即它总是返回 >= 1 成功) . std::wstring 的长度构造函数不需要这个。 std::wstring(5,0) 将为六个宽字符分配空间; 5+零项。所以从技术上讲,您分配的宽字符太多了。

来自 MultiByteToWideChar cbMultiByte 和 -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.

关于c++ - 这段代码将 wstring 与 MultiByteToWideChar 结合使用是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14184709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com