簡體   English   中英

將std :: string轉換為const tchar *

[英]convert std::string to const tchar*

我有一個函數,它接受一個名為arrayOfStrings的參數,定義如下:

const TCHAR* arrayOfStrings[] = { L"Test" };

現在,我想將字符串轉換為上述類型,但是我不知道如何。 該鏈接提供了將字符串轉換為tchar而不是const tchar *的解決方案。 另一個鏈接顯示了如何將字符串轉換為tchar *,而不是const tchar *,第二種解決方案對我來說是內存分配的問題。 您可能會說,我對c ++還是很陌生,所以任何教育技巧也將不勝感激。

一種適用於所有C ++標准的簡單方法是

 #include <string>

 #include <windows.h>    //   or whatever header you're using that specifies TCHAR

 int main()
 {
       std::string test("Hello");     //   string to be converted

       //   first, if you need a const TCHAR *

       std::basic_string<TCHAR> converted(test.begin(), test.end());

       const TCHAR *tchar = converted.c_str();

       //   use tchar as it is in the required form (const)

       //   second, if you need a TCHAR * (not const)

       std::vector<TCHAR> converted2(test.begin(), test.end());

       TCHAR *tchar2 = &converted2[0];

       // use tchar2 as it is of the required form (non-const).

 }

std::basic_string並非在所有C ++標准中都提供一種獲取指向其數據的非const指針的方法,但std::vector卻提供了一種方法。 (假設您不使用顯式轉換來引入或刪除const )。

在C ++ 17和更高版本中,事情變得更簡單: basic_string::data()同時具有const和非const重載,這在2017年標准之前不是這種情況。 在C ++ 11之前,標准不保證basic_string的數據是連續的(即使實現通常以這種方式實現),但是c_str()確實提供了連續數組的第一個字符的地址。 最終的結果是,在C ++ 17和更高版本中,可以使用basic_string::data()basic_string::c_str()適當重載,而無需強制轉換來更改const ,也無需使用vector (已保證在所有C ++標准中它們都具有連續的元素)。

兩種情況下的注意事項

  1. 如果指針( tchartchar2 )各自的容器( convertedconverted2 )被調整大小或不再存在,則它們將無效。 例如,不使用數據指向tchar如果converted已經傳遞出的范圍,因為數據tchar在將不復存在點。
  2. 使用指針運行到最后是完全未定義的行為(使用指針時沒有神奇的大小調整)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM