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