Nominate our 2022 Qt Champions!

[SOLVED] Problem using QTextStream as local variable

  • Here is the code and problem I am experiencing in a method I have. Like any responsible programmer I want to make sure that I do not let a dangling pointer go undeleted...

    public someFunction()
    QByteArray* mResponse = new QByteArray();
    QTextStream outds(mResponse, QIODevice::WriteOnly);

    // do something with stream/array

    delete mResponse; // doesn't cause error directly BUT

    } // error occurs here when leaving the method if I delete mResponse.

    Basically if I delete mResponse, the program crashes upon leaving the method giving an Access Violation. The only reason I can think of for this is that QTextStream attempts to delete the QByteArray as part of its destruction... a pointer that has already been deleted. Is this true?

  • No, QTextStream doesn't delete the QByteArray, but QTextStream::flush() will be called when destroys the QTextStream.

  • Lifetime Qt Champion


    To add to 1+1=2, you don't need to allocate mResponse on the heap

    QByteArray mResponse;
    QTextStream outds(&mResponse, QIODevice::WriteOnly);

    // do something with stream/array

    is the usual pattern in this case

Log in to reply