Glib::ustring

You might be surprised to learn that gtkmm doesn't use std::string in its interfaces. Instead it uses Glib::ustring, which is so similar and unobtrusive that you could actually pretend that each Glib::ustring is a std::string and ignore the rest of this section. But read on if you want to use languages other than English in your application.

std::string uses 8 bit per character, but 8 bits aren't enough to encode languages such as Arabic, Chinese, and Japanese. Although the encodings for these languages have now been specified by the Unicode Consortium, the C and C++ languages do not yet provide any standardised Unicode support. GTK+ and GNOME chose to implement Unicode using UTF-8, and that's what is wrapped by Glib::ustring. It provides almost exactly the same interface as std::string, along with automatic conversions to and from std::string.

UTF-8 编码的优点之一是,如果不需要你可以不使用它,所以你不需要一次性的翻新你的代码。std::string 还可以继续使用7位的 ASCII 字符串。但是一旦你想本地化你的程序,比如说汉化,那你就会开始遇到各种奇怪的问题,可能还会崩溃。那时,你所需要做的就是开始使用 Glib::ustring 来取而代之。

要注意的是 UTF-8 和其它一些8位的编码如 ISO-8859-1 并不兼容。比如,德语中的元音变音并不在 ASCII 码的编码范围内,在 UTF-8 编码中需要额外的一个字节来表示。如果你的代码中包含8位的字符串文字,你需要把它们转变成 UTF-8 编码 (比如,巴伐利亚的问候语“Grüß Gott”可能会显示成“Gr\xC3\xBC\xC3\x9F Gott”)。

你应该尽量避免 C 风格的指针算法,以及像 strlen() 这样的函数。在 UTF-8 编码中,每个字符可能占1到6个字节,所以你并不能假定下一个字节一定是另一个字符。所有的这些细节 Glib::ustring 都已经帮你考虑到了,所以你可以从字符的层面上考虑使用 Glib::ustring::substr() 这样的函数,而不用再去考虑字节这样的细节了。

不像 Windows 的 UCS-2 Unicode 解决方案,这并不需要编译器提供特别的选项来处理这样字符串,也不会导致为 Unicode 编译的可执行文件或库与含为 ASCII 的不兼容之类的问题。

Reference

要得到更多关于 UTF-8 字符的信息,请参考国际化这一节。