![](/img/trans.png)
[英]Proper way crossplatfom convert from std::string to 'const TCHAR *'
[英]convert std::string to const tchar*
一種適用於所有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 ++標准中它們都具有連續的元素)。
兩種情況下的注意事項
tchar
和tchar2
)各自的容器( converted
或converted2
)被調整大小或不再存在,則它們將無效。 例如,不使用數據指向tchar
如果converted
已經傳遞出的范圍,因為數據tchar
在將不復存在點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.