c++qtqstringqtextstream

Ownership of QString with QTextStream


I am trying to use QTextStream to read from a QString. Since the constructor has the following signature:

    QTextStream(QString *string, QIODevice::OpenMode openMode = QIODevice::ReadWrite)

(see the documentation)

Since the constructor is passed a raw pointer, I wonder if the QTextStream takes ownership of the QString or if I have to manage it in my code to ensure that the QString object is deleted after the QTextStream object.

I haven't found any information on this neither in the documentation nor on search engines (e.g. google, duckduckgo). All examples I have found show a QString and a QTextStream that have the same lifetime (local variables in the same function), so I am not sure what happens if the two objects have different lifetimes.


Solution

  • The QTextStream doesn't take the ownership of the QString.

    In fact you can write a function like this:

    void test()
    {
        QString s;
        QTextStream ts(&s);
        ///.....
    }
    

    If the QTextStream takes the ownership, in this case the QString would be deleted two times, and there would be a runtime error. But this code is correct, so the QTextStream doesn't take the ownership