1. 程式人生 > >wstring 和 wchar_t* 轉換(處理const)

wstring 和 wchar_t* 轉換(處理const)

  1. {  
  2. }  
  3. int _tmain(int argc, _TCHAR* argv[])  
  4. {  
  5.     std::wstring dest;  
  6. const std::string src;  
  7. int destSize = 0;  
  8. int srcSize = (int) src.length();  
  9. wchar_t dummy;  
  10. // compute size
  11.     Process((const unsigned char*) src.c_str(), srcSize, &dummy, &destSize);  
  12. //option 1-bad
  13.     dest.resize(destSize);  
  14.     Process((const unsigned char*) src.c_str(), srcSize, (wchar_t*)dest.c_str(), &destSize);  
  15. //option 2-also bad
  16.     dest.resize(destSize);  
  17.     Process((const unsigned char*) src.c_str(), srcSize, const_cast<wchar_t*>(dest.c_str()), &destSize);  
  18. //option 3-good
  19. wchar_t* destChars = newwchar_t
    [destSize+1];  
  20.     destChars[destSize] = L'\0';  
  21.     Process((const unsigned char*) src.c_str(), srcSize, destChars, &destSize);  
  22.     dest = std::wstring(destChars);  
  23. delete destChars;  
  24. return 0;  
  25. }  

三種方法都可以編譯通過。

[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,清理動態分配記憶體