一个天天跟c#奋斗的苦逼c++程序猿 改自己曾经代码的时候发现有例如以下几行.
char szPath[MAX_PATH] = {0};
GetModuleFileNameA(NULL,szPath,sizeof(szPath));
std::string strPath = szPath;
std::string strDir = strPath.substr(0,strPath.find_last_of('\'));
感觉不爽了,怎么又有char数组 又有string,都用string岂不是更好.
于是改为例如以下代码:
std:: strPath;
strPath.reserve(MAX_PATH);
GetModuleFileNameA(NULL,&strPath[0],MAX_PATH);
std::string strDir = strPath.substr(0,strPath.find_last_of('\'));
OK 改完了. 一跑.........尼玛功能变了.你懂的.......
strDir为空.
为啥捏,strPath里面尽管有内容了,但API不会给string的size赋值啊.
假设想正确的用string取代char数组,仅仅能採用以下的方式.
std:: strPath;
strPath.resize(MAX_PATH,0);
GetModuleFileNameA(NULL,&strPath[0],strPath.size());
strPath.asign(strPath.c_str()); //又一次赋值.
这..........不是拖了裤子放屁吗?