wstring 和 wchar_t* 轉換(處理const)
阿新 • • 發佈:2019-01-30
- {
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- std::wstring dest;
- const std::string src;
- int destSize = 0;
- int srcSize = (int) src.length();
- wchar_t dummy;
- // compute size
- Process((const unsigned char*) src.c_str(), srcSize, &dummy, &destSize);
- //option 1-bad
- dest.resize(destSize);
- Process((const unsigned char*) src.c_str(), srcSize, (wchar_t*)dest.c_str(), &destSize);
- //option 2-also bad
- dest.resize(destSize);
- Process((const unsigned char*) src.c_str(), srcSize, const_cast<wchar_t*>(dest.c_str()), &destSize);
- //option 3-good
- wchar_t* destChars = newwchar_t
- destChars[destSize] = L'\0';
- Process((const unsigned char*) src.c_str(), srcSize, destChars, &destSize);
- dest = std::wstring(destChars);
- delete destChars;
- return 0;
- }
三種方法都可以編譯通過。
[option 1]
dest.c_str() 得到C風格的以null結尾的字串形式,以const修飾。(wchar_t*)dest.c_str() 強制去掉const。首先(casted type)variable 是C風格的轉換,在cpp原始檔中最好使用C++風格的轉換,即specific_cast<casted type>(variable),specific_cast就是static_cast, const_cast, reinterpret_cast等。
用g++編譯,開啟-Wcast-qual 開關,會有warning。
$g++ -Wcast-qual test.cpp
warning: cast from type 'const wchar_t*' to type 'wchar_t*' casts away qualifiers
-Wcast-align
Warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a
char *
is cast to an int *
on machines where integers can only be accessed at two- or four-byte boundaries.
[option 2]
使用了C++風格的轉換,用const_cast去掉了const屬性。
option 1 和 option 2 都是不好的編碼風格。儘量不要用。
[option 3]
推薦使用。先分配wchar_t*,使用,複製給wstring,清理動態分配記憶體