将此代码与 MultiByteToWideChar 一起使用 wstring 是否安全? [英] Is this code safe using wstring with MultiByteToWideChar?

查看:22
本文介绍了将此代码与 MultiByteToWideChar 一起使用 wstring 是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using std::wstring the way I am with 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;
}

推荐答案

如果你问它是否有效,可能.这是正确的吗?

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

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

来自 MultiByteToWideChar 关于 cbMultiByte 和 -1 的文档:

From MultiByteToWideChar docs on cbMultiByte and -1:

如果此参数为 -1,则函数处理整个输入字符串,包括终止的空字符.因此,生成的Unicode字符串有一个终止空字符,函数返回的长度包括这个字符.

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.

这篇关于将此代码与 MultiByteToWideChar 一起使用 wstring 是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆