wchar_t*奇怪的行为
wchar_t* weird behavior
本文关键字:wchar 更新时间:2023-10-16
嗨,我正在寻求一些建议我在类的命令解释器中工作,我有这个"命令"(这是一个类),它从内部变量中获取一些 C 字符串并创建一个 std::wstring,然后我将其转换为 wchar_t * 但是当我返回它时,我只得到变量上的垃圾,p.e
返回前变量的内容:
Comandos disponibles: Ayuda Salir
返回后变量内容:
����������������������������������������
我试图让函数返回一个常量 wchar_t *,但它也不起作用,但是如果我在返回中放一个字符串,它就可以正常工作。
return L"test"
知道吗?
--编辑--
这是我正在使用的代码
wchar_t * ayuda::run(std::list<char* const> * lista){
std::wstring out;
out += L"comandos disponibles:n"; //static header
commandMap map = loadMap();//get a map whit all the function names
commandMap::iterator it;
for(it = map.begin(); it != map.end();it++){
out+=std::wstring(it->first.begin(),it->first.end())+L"n";// append the command name to the string
}
wchar_t * _out = const_cast<wchar_t*>( out.c_str() ); //cast to wchar *
return _out;
}
您是否正在尝试返回堆栈上分配的wchar_t *?
wchar_t *MyFunction()
{
wchar_t myString[] = L"This will be destroyed from the stack on returned";
return myString;
}
在这种情况下,将从堆栈中删除字符串,然后返回垃圾。这将解释你所看到的。
在C++中,对字符串使用 std::string 或 std::wstring,它可以防止内存泄漏并提供有用的功能。尽可能避免使用数组。
#include <string>
std::wstring MyFunction()
{
std::wstring myString = L"This will be copied, since this is not a pointer, but an instance of an object.";
return myString;
}
另一种方法是在堆上分配字符串,然后您需要确保在某处删除它,否则会出现内存泄漏。
wchar_t *MyFunction()
{
wchar_t myString[] = L"This will be destroyed from the stack on returned";
size_t myStringLen = wcslen(myString);
wchar_t *outString = new wchar_t[myStringLen+1]; //allocate heap memory
wcscpy(outString, myString); //copy the string to heap memory
return outString; //return a string that will not be destroyed.
}
相关文章:
- MacOS通过在莫哈韦"wchar.h"下破碎的自制啤酒发出叮当声
- VS Code C++:不准确的系统包括路径错误(wchar.h,boost/lambda/lambda.hpp)
- 'const char*'和'WCHAR*'
- 为什么需要与 WCHAR 相关的代码处理
- 无法使用 mingw-w64 g++ 编译:找不到 <wchar.h>
- 无法将参数 1 从 WCHAR 转换为常量字符 *
- 无法使用 swprintf 在 WCHAR* 中打印字符*
- -fshort-wchar 和 std::wstring - 分段错误
- 我应该使用 wchar 还是 char 来加密?
- 【MacOSX 10.15.1】使用 odb 生成数据库,致命错误:wchar.h:没有这样的文件或目录 #include < wchar.h>
- 如何在 C++ 中的 wcstok 中使用常量 WCHAR* 变量?
- 将字符串文本常量定义为 char const* 和 wchar const*
- 比较嵌套 for 循环中的两个 wchar 数组?
- wchar 模式下 pugixml 的链接错误
- strcmp 错误'WCHAR [260]' 'const char *'
- 'Cannot add two pointers'添加带有 WCHAR 的 LPCWSTR
- 如何将CString转换为使用WCHAR的Windows API和自定义函数?
- 从网络数据包复制一串 wchar 时访问冲突
- 如何使用 Win32 WCHAR 执行字符串操作
- VC++ 2017 如何将常量wchar_t转换为 WCHAR *.