如何使用QString Toutf8和FromutF8

How to use QString toUtf8 and fromUtf8?

本文关键字:FromutF8 Toutf8 QString 何使用      更新时间:2023-10-16

我有一个奇怪的问题:

    QString s1="abc";
    const char * ss1=s1.toUtf8().constData();
    QString s2=QString::fromUtf8(ss1);
    if(s1==s2)
      qDebug()<<"s1==s2";
    else
      qDebug()<<"s1!=s2";

上述代码的输出为" S1!= S2"。实际上,SS1和S2的内容是一团糟。但是以下代码的输出为" S1 == S2"。为什么?

    QString s1="abc";
    QString s2=QString::fromUtf8(s1.toUtf8().constData());
    if(s1==s2)
      qDebug()<<"s1==s2";
    else
      qDebug()<<"s1!=s2";

,因为您的代码中的行为不确定:

const char * ss1 = s1.toUtf8().constData();

toUtf8()函数返回的QByTearray是一个临时对象,并被破坏。但是您将指针保留到其数据,然后尝试使用:

QString s2=QString::fromUtf8(ss1);

这会导致不确定的行为。

为此,您需要保持临时的QByTearray对象。您可以为此使用const引用。它将延长临时对象的寿命:

QString s1 = "abc";
const auto& bytes = s1.toUtf8();
const char * ss1 = bytes.constData();

您的第二个示例很好,因为您没有使用任何指针来对被破坏对象的内部记忆:

QString s2 = QString::fromUtf8(s1.toUtf8().constData());

toUtf8()返回的临时QbyTearray对象仅在 返回 fromUtf8()返回之后被销毁。因此,constData()指针有效期足够长,可以允许函数读取数据。