![](/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.