c++ - 类型转换 char* -> QString,可读性还是清晰度? (C++/Qt)

标签 c++ qt casting

我正在尝试将 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/

相关文章:

java - C++ 客户端连接到非阻塞 Java NIO 服务器

c++ - 为什么qt不读取文件

c++ - 从我的类(class)转换为 int

c++ - 哪个 C++ 库提供带有不强制执行比较函数的任何类型的键的映射?

c++ - 是否有可能在 C++ 中使用函数指针获得早期/静态绑定(bind)?如果是那么如何?

c++ - 从 SoundTouch 音频库转换 short[] 以进行播放

python-3.x - PyQt5 - 如何在鼠标点击位置画一个点?

qt - Qt OpenGL 小部件中的 3D 模型 (.3ds)

c# - 在调用 Dispose() 之前转换为 IDisposable

java - 从 getAdapter 到我的泛型类的转换如何进行