简体   繁体   English

QString转换为const char *的结果不同

[英]Different results for QString to const char*

I have a code snippet to test a code bug. 我有一个代码片段来测试代码错误。

    #include <QCoreApplication>
    #include <QDebug>

    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QString name = QString("Lucy");
        QString interest = QString("Swimming");

        const char* strInterest = interest.toLatin1().data();
        const char* strName = name.toLatin1().data();

        qDebug()<<"QName: "<<name<<" QInterest: "<<interest;
        qDebug()<<"Name: "<<strName<<" Interest: "<<strInterest;

        return a.exec();
    }

The result on macOS : QName: "Lucy" QInterest: "Swimming" Name: Lucy Interest: . macOS上的结果: QName: "Lucy" QInterest: "Swimming" Name: Lucy Interest:

The result on ubuntu : root@:test$ ./testCharP QName: "Lucy" QInterest: "Swimming" Name: Interest: . ubuntu上的结果: root@:test$ ./testCharP QName: "Lucy" QInterest: "Swimming" Name: Interest:
As you can see, the converted buffer does not be saved as a const value, what about the problem? 如您所见,转换后的缓冲区不会保存为const值,那该怎么办? Also, there are some differences between these two OS, what is the cause maybe?. 另外,这两个操作系统之间存在一些差异,可能是什么原因?

What you are observing is undefined behavior. 您正在观察的是未定义的行为。

The call to toLatin1() creates a temporary QByteArray , which is destroyed immediately after that line, since you do not store it. 调用toLatin1()会创建一个临时QByteArray ,该行在该行之后立即销毁,因为您没有存储它。 The pointer obtained by data() is left dangling and might or might not print something useful. data()获得的指针悬空了,可能会或可能不会打印出有用的东西。

Correct version: 正确版本:

const QByteArray& latinName = name.toLatin1();
const char* strName = latinName.data();

The problem is that the toLatin1 function returns a QByteArray object, and by not saving this object it will be temporary and be destructed once the assignment have been done. 问题在于toLatin1函数返回一个QByteArray对象,并且不保存该对象将是临时的,并且在分配完成后将被销毁。

That means your pointer points to some data that no longer exists, and dereferencing it will lead to undefined behavior . 这意味着您的指针指向了一些不再存在的数据,对其取消引用将导致未定义的行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM