C++ 奇怪的行为

C++ 奇怪的行为,c++,visual-c++,corruption,garbage,C++,Visual C++,Corruption,Garbage,嗨,我想听听你的建议 我在一个类的命令解释器中工作,我有一个“命令”(这是一个类),它从内部变量中获取一些c字符串,并生成一个std::wstring,然后我将它转换为wchar_t*,但当我返回它时,我只得到变量上的垃圾,p.e 返回前变量的内容: comandos争议:ayuda salir 返回后变量的内容: ���������������������������������������� 我试图让函数返回一个常量wchar\u t*,但它也不起作用,但如果我在返回中放入一个字符串,它就可

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

返回前变量的内容:

comandos争议:ayuda salir

返回后变量的内容:

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

我试图让函数返回一个常量wchar\u 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*ayuda::run(std::list*lista){
std::wstring out;
out+=L“comandos可分配文件:\n”;//静态标头
commandMap=loadMap();//获取包含所有函数名的映射
commandMap::迭代器;
for(it=map.begin();it!=map.end();it++){
out+=std::wstring(it->first.begin(),it->first.end())+L“\n”//将命令名附加到字符串中
}
wchar_t*_out=const_cast(out.c_str());//转换为wchar*
退出;
}

是否尝试返回堆栈上分配的wchar\u 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;
}

首先,不要抛弃它。c_str()是您的朋友。我已经在使用它了,请查看更新您正在返回的
\u out
,它指的是
out。c_str
,但是
out
将不在范围内,它的析构函数将被调用,因此
\u out
不再有意义。我更新了原始日志以包含我的代码,我将尝试解决heapNo问题!但是,我认为返回std::wstring是一种更好的做法,而不是返回wchar\u t*。但这取决于你。
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.
}