0

嗨,我正在寻找一些建议,我在类的命令解释器中工作,我有这个“命令”(即一个类),它从内部变量中获取一些 c 字符串并创建一个 std::wstring,然后我将它转换为 wchar_t *但是当我返回它时,我只会在变量上得到垃圾,pe

返回前变量的内容:

comandos disponibles: ayuda salir

返回后变量的内容:

������������������������������������������

我试图让函数返回一个 const 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;
}
4

1 回答 1

1

您是否试图返回分配在堆栈上的 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.
}
于 2012-09-15T01:11:13.413 回答