如何最好地利用wsup
How do you best utilize wcsdup?
我正在编写代码,其中很大一部分需要返回wchar数组。返回字符串并不是一个真正的选项(尽管我可以使用它们),我知道我可以传递一个指针作为参数并填充它,但我特别想返回一个指向这个宽字符数组的指针。在最初的几次迭代中,我发现我可以正确地返回数组,但是当它们被处理和打印时,内存将被覆盖,我将留下乱码。为了解决这个问题,我开始使用wssdup,它修复了所有问题,但我很难准确地掌握发生了什么,因此,什么时候应该调用它,以便它能够工作,并且不会泄漏内存。实际上,每次返回字符串和每次返回字符串时,我都会使用wsup,我知道这会泄漏内存。这就是我正在做的。我应该在哪里以及为什么使用wsdup,或者是否有比wsdup更好的解决方案?
wchar_t *intToWChar(int toConvert, int base)
{
wchar_t converted[12];
/* Conversion happens... */
return converted;
}
wchar_t *intToHexWChar(int toConvert)
{
/* Largest int is 8 hex digits, plus "0x", plus /0 is 11 characters. */
wchar_t converted[11];
/* Prefix with "0x" for hex string. */
converted[0] = L'0';
converted[1] = L'x';
/* Populate the rest of converted with the number in hex. */
wchar_t *hexString = intToWChar(toConvert, 16);
wcscpy((converted + 2), hexString);
return converted;
}
int main()
{
wchar_t *hexConversion = intToHexWChar(12345);
/* Other code. */
/* Without wcsdup calls, this spits out gibberish. */
wcout << "12345 in Hex is " << hexConversion << endl;
}
wchar_t *intToWChar(int toConvert, int base)
{
wchar_t converted[12];
/* Conversion happens... */
return converted;
}
返回指向局部变量的指针。
wchar_t *hexString = intToWChar(toConvert, 16);
在这行之后,hexString
将指向无效内存,并且使用它是未定义的(可能仍然有值,也可能是垃圾!)
对intToHexWChar
的返回做同样的事情。
解决方案:
- 使用
std::wstring
- 使用
std::vector<wchar_t>
- 传递一个数组给函数,让它使用
- 使用智能指针
- 使用动态内存分配(请不要!)
注意:您可能还需要更改为wcout
而不是cout
既然你用' c++ '标记了你的问题,答案是一个响亮的:不,你根本不应该使用wcsdup
。相反,对于传递wchar_t
值的数组,请使用std::vector<wchar_t>
。
如果需要,可以通过取第一个元素的地址将它们转换为wchar_t*
(因为vector保证存储在连续内存中),例如
cout << "12345 in Hex is " << &hexConversion[0] << endl;
相关文章:
- 函数何时会在c++中包含stack_Unwind_Resume调用
- Python中的for循环与C++有何不同
- 在C++中释放内存期间,迭代器与指针有何不同
- 如何在C++中最好地实施"newtype"成语?
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 类中的 C++ int 被设置为值,似乎不知从何而来
- -fvisibility-inline-hidden 与 gcc 中的 -fvisibility=hidden 有何不同
- C++模板元编程(版本小于 17,最好是 11)
- 哪一个是最好的方法类或结构?在 C++ 中
- 可视化如何在我的C++程序中最好地使用相同的Boost日志
- 如何最好地让用户重新定义类方法
- 收益率和回报有何不同?
- 覆盖私有功能,它与受保护功能有何不同?
- 如何最好地将 emplace 与 std::map 一起使用
- 擦除删除成语的性能增益从何而来
- 无论代码长度如何,以下代码的内存要求有何不同?
- "virtual"对C++析构函数有何影响?
- 如果我对"while"块发表评论,为什么程序会死机?其中的"yield"线有何影响?
- 系统时间从何而来?
- 如何最好地利用wsup