Search code examples
c++qtpointersqstringqmap

const char* wrong behavior in Qt


I have a problem with returning a const char* from two functions from a class, by some reason the first value is a replica of the second value or some values is wrong, but both values returned are from different pointers, in this case two QMap, the following is the code of the two functions:

const char* SomeClass::getSignal(QString signalName)
{
    QString signalsignature = this->signals.value(signalName);
    signalsignature.prepend(QString::number(QSIGNAL_CODE));
    QByteArray ba = signalsignature.toLatin1(); // i try toUTF8 and to Local8Bit
    const char* signalformated = ba.constData();
    return signalformated;
}

const char* SomeClass::getSlot(QString slotName)
{
    QString slotsignature = this->slots.value(slotName);
    slotsignature.prepend(QString::number(QSLOT_CODE));
    QByteArray ba = slotsignature.toLatin1();
    const char* slotformated = ba.constData();
    return slotformated;
}

The this->slot and the this->signals are QMap<QString, QString> that save slots and signals signatures ( somesignal(int) or someslot(bool) with keys somesignal, someslot respectively).

The class that i use is loaded from a DLL by QLibrary using an interface, all works fine using other functions from it, but using these functions like this:

const char* signal = someclassinstance->getSignal(tr("clicked"));
const char* slot = someclassinstance->getSlot(tr("onclicked"));

cout << "connecting signal " << signal << " to slot " << slot << endl;

this show me:

connecting signal clicked to slot rc

and the error when i use QObject::connect

Object::connect: Use the SLOT or SIGNAL macro to connect NovaRadioButton:: rc

I fill the QMaps is some function with:

signals.insert(methodname,QString(metamethod.signature()));

I don't know what i am doing wrong or if maybe is a bug in Qt functions from QString, thanks for your help.


Solution

  • When your functions exit, the ba objects are destroyed. The pointers you return point inside memory locations of no longer existing objects. This is the basic (and well known) error of returning pointers to locals:

    char* foo()
    {
        char c = 'a';
        return &c;
    }
    

    The fact that you're dealing with a QByteArray doesn't matter; it's still an automatic, local variable and thus gets destroyed on function exit.

    You should instead return a QByteArray directly, not a char*. This is still efficient, since QByteArray uses implicit sharing.