c++ - 与遗留 TCHAR 代码接口(interface)的正确样式

标签 c++ windows winapi wchar-t tchar

我正在修改广泛使用 TCHAR 的其他人的代码。在我的代码中只使用 std::wstring 是否更好? wstring 应该等同于 widechar 平台上的 TString,所以我看不出有什么问题。理由是,使用原始 wstring 比支持 TCHAR 更容易……例如,使用 boost:wformat。

下一个维护者会更清楚哪种风格?我自己浪费了几个小时试图理解字符串的复杂性,似乎只使用 wstring 就会减少你需要理解的一半内容。

typedef std::basic_string<TCHAR> TString; //on winxp, TCHAR resolves to wchar_t
typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> > wstring;

...唯一的区别是分配器。

In the unlikely case that your program lands on a Window 9x machine, there's still an API layer that can translate your UTF-16 strings to 8-bit chars. There's no point left in using TCHAR for new code development. source

最佳答案

如果您只打算针对 Unicode (wchar_t) 平台,您最好使用 std::wstring。如果你想支持多字节和 Unicode 构建,你将需要使用 TString 和类似的东西。

另请注意,basic_string 根据传入的字符类型将 char_traits 和分配器默认为一个,因此在 UNICODE(或 _UNICODE,我永远记不起是哪个)的构建中,TString 和 wstring 将相同。

注意:如果您只是将参数传递给各种 API,而不对它们进行任何操作,您最好使用 const wchar_t * 而不是直接使用 std::wstring(特别是如果混合使用 Win32 、COM 和标准 C++ 代码),因为您最终将减少转换和复制。

关于c++ - 与遗留 TCHAR 代码接口(interface)的正确样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3241645/

相关文章:

.net - 默认 IMarshal 实现?

css - rake Assets :precompile not working - Windows 7

c++ - Windows API 函数 CredUIPromptForWindowsCredentials 也返回错误 31

c++ - 暂停后无法恢复流程

c - C和Windows API有什么关系?

c++ - 如何编写 C++ 库以与 span<T> 的任何实现一起工作?

c++ - 动态转换还是函数重载?

c++ - 我是否在头文件中正确地创建了一个对象?

php - 在 WIndows Apache 2.4 中安装 casperJS 和 phantomJS 向 PHP 传递数据

c++ - 与size_t比较,返回int?