2012-09-15 72 views
0

嗨im歡呼的一些建議 im工作在類的命令解釋器,我有這個「命令」(這是一個類),從內部變量獲取一些c字符串,並使std :: wstring ,然後我投它爲wchar_t *但是當我回到我得到它的變量只是垃圾,回來之前PEwchar_t *奇怪的行爲

內容變量:

comandos disponibles:ayuda salir

內容返回後的變量:

我試圖讓函數返回一個常量wchar_t *但它也不工作,但如果我把一個字符串放在返回它只是工作罰款PE。

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; 
} 
+0

首先,不要施放它。 .c_str()是你的朋友。 – WhozCraig

+0

我已經在使用它,請參閱更新 –

+0

您正在返回引用'out.c_str'的​​'_out',但'out'將會超出範圍並且它的析構函數會被調用,所以'_out'不再有意義。 – oldrinb

回答

1

你試圖返回在棧上分配一個wchar_t的*代碼i'm?

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

我更新了原始郵件包括我的代碼,我會盡量堆堆 –

+0

堆事情工作,謝謝! –

+0

沒問題!不過,我認爲返回一個std :: wstring是一種更好的做法,而不是wchar_t *。但這取決於你。 – aStranger