What's the purpose of QString?

2019-07-13 06:09发布

问题:

I'm a newcomer to C++ and Qt. I've been messing around with Qt Creator for a few days, and what really struck me was how the GUI components only accepted a const QString& rather than a string or an std::wstring. To stay consistent with this, I've been trying to accept and return QString from most of my function calls, however I find myself converting to and from std::string a lot to use most of the standard library facilities.

My question here is, what's the purpose of QString if std::string is part of the standard library? I guess this would be beneficial to someone who was already using Qt and didn't want another dependency on #include <string>, but to be honest you'll need std::string if you want to do anything useful with your application. (This especially goes for QChar, since char is a builtin.)

Can someone explain to me why this is not reinventing the wheel and how this helps being cross-platform?

回答1:

My question here is, what's the purpose of QString if std::string is part of the standard library?

Reasons that I can think of:

  1. QString has been part of the Qt library way before std::string came to life.

  2. Its interface includes a lot of Qt specific classes. Hence, the usage of QString cannot be easily replaced by std::string.

  3. Its interface is a lot richer than std::string.



回答2:

One advantage of QString over std::string is that it's easier to write platform-independent code. For Unicode support most platforms use UTF-8 encoding, whereas Windows uses UTF-16 encoding.

Adding to the confusion, while a char is the same size on all platforms wchar_t is not. So the size of a character in std::wstring will vary from platform to platform.

QString eliminates this confusion by using UTF-16 encoding on all platforms. If you need to interact with platform-specific code, QString provides helper methods to convert to and from UTF-8, UTF-32, native std types, etc.



标签: c++ string qt std