我正在尝试将 testclasses
添加到现有的 Qt 项目中,我遇到了这个问题:
void doSomething (QString str, int i) {..}
int main () {
//Do I use
doSomething("string", 0);
//Or
doSomething(QString("string"), 0);
}
如果我没记错的话,它在内部做同样的事情,因为它使用 QString(char* c)
构造函数隐式转换 char*
。
但哪种方式更受欢迎?
我个人喜欢隐式转换,因为它比构造函数调用更容易阅读,但在我阅读的 C++ 书中,应尽可能避免隐式转换。
最佳答案
实际上,如果您使用的是 Qt5,更好的方法是 QStringLiteral()
。它不仅表明了意图(编译时常量 QString
),而且(略微)提高了效率,因为不需要从某些多字节编码到 UTF-16 的运行时转换。
如果需要使用Qt4,那么有条件的自己定义:
#ifndef QStringLiteral
#define QStringLiteral(x) (QString::fromUtf8(x))
#endif
或者按照 Kuba Ober 的评论,添加
lessThan(QT_MAJOR_VERSION, 5): DEFINES += QStringLiteral=QString::fromUtf8
到您的 .pro 文件。
引自Qt文档:
The macro generates the data for a QString out of str at compile time if the compiler supports it. Creating a QString from it is free in this case, and the generated string data is stored in the read-only segment of the compiled object file.
For compilers not supporting the creation of compile time strings, QStringLiteral will fall back to QString::fromUtf8().
If you have code looking like:
if (node.hasAttribute("http-contents-length")) //...
One temporary QString will be created to be passed as the hasAttribute function parameter. This can be quite expensive, as it involves a memory allocation and the copy and the conversion of the data into QString's internal encoding.
This can be avoided by doing
if (node.hasAttribute(QStringLiteral("http-contents-length"))) //...
Then the QString's internal data will be generated at compile time and no conversion or allocation will occur at runtime
Using QStringLiteral instead of a double quoted ascii literal can significantly speed up creation of QString's from data known at compile time.
If the compiler is C++11 enabled the string str can actually contain unicode data.
关于c++ - 类型转换 char* -> QString,可读性还是清晰度? (C++/Qt),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25892541/