与遗留 TCHAR 代码接口的正确样式 [英] proper style for interfacing with legacy TCHAR code

查看:24
本文介绍了与遗留 TCHAR 代码接口的正确样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm modifying someone else's code which uses TCHAR extensively. Is it better form to just use std::wstring in my code? wstring should be equivalent to TString on widechar platforms so I don't see an issue. The rationale being, its easier to use a raw wstring than to support TCHAR... e.g., using boost:wformat.

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

Which style will be more clear to the next maintainer? I wasted several hours myself trying to understand string intricacies, it seems just using wstring would cut off half of the stuff you need to understand.

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;

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

...the only difference is the allocator.

在不太可能的情况下,您的程序降落在 Window 9x 机器上,有仍然是一个可以翻译的API层将 UTF-16 字符串转换为 8 位字符.使用 TCHAR 没有任何意义用于新代码开发.

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 和类似的.

If you are only intending on targetting Unicode (wchar_t) platforms, you are better off using std::wstring. If you want to support multibyte and Unicode builds, you will need to use TString and similar.

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

Also note that basic_string defaults the char_traits and allocator to one based on the passed in character type, so on builds where UNICODE (or _UNICODE, I can never remember which), TString and wstring will be the same.

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

NOTE: If you are just passing the arguments to various APIs and not doing any manipulations on them, you are better off using const wchar_t * instead of std::wstring directly (especially if mixing Win32, COM and standard C++ code) as you will end up doing less conversions and copying.

这篇关于与遗留 TCHAR 代码接口的正确样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆