繁体   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