[英]c++ const_cast<char*> same binary different results on 2 64bit ms os's
我具有以下功能(為簡便起見,簡稱:)(端口號= 12345)
void startparser(){
std::ostringstream convert;
convert.str("");
convert << '"' << "c:\\some\\file path\\a_program.exe" << '"' << " " << PortNo;
std::cout << "DEBUG2 " << convert.str() <<std::endl;
char *cmd = const_cast<char*> ( convert.str().c_str() );
std::cout << "DEBUG3 " << cmd <<std::endl;
}
我用Eclipse MinGW64和代碼輸出在w10 64bit上編譯
DEBUG2“ c:\\ some \\ file path \\ a_program.exe” 12345
DEBUG3“ c:\\ some \\ file path \\ a_program.exe” 12345
現在,如果我將二進制文件和3個dll復制到Win7 64計算機上並運行相同的代碼,
DEBUG2“ c:\\ some \\ file path \\ a_program.exe” 12345
調試3。
我不明白嗎? 我需要cmd才能成為LPTSTR。 有人可以澄清一下嗎? 獲得我的LPTSTR的另一種方法也很好。
您正在使用一個臨時對象: ostringstream::str()
返回一個立即被銷毀的對象。 因此,在此行之后
char *cmd = const_cast<char*> ( convert.str().c_str() );
cmd
指向用於臨時對象的內存,因此不再有效。
如果確實需要使用const char*
進行操作,則需要創建一個中間string tmp = convert.str()
。 然后,指向tmp.c_str()
的指針將在tmp
的整個范圍內有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.