0

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.

giorgio-b
  • 113
  • 7
  • 1
    I haven't used `QTextStream` using this particular constructor. However, I think that the `QTextStream ` object merely uses the `QString` to read from or write to. It does not take ownership of the `QString`. – R Sahu Jun 09 '16 at 15:34

2 Answers2

3

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

Fabio
  • 2,522
  • 1
  • 15
  • 25
3

If the documentation doesn't specifically state that the QTextStream object takes ownership, it's fairly safe to assume that it doesn't. It would be a pretty nasty omission otherwise.

But if you don't trust the documentation to inform you, you have two recourses: read the source code or test the behaviour in code.

As it turns out, QTextStream doesn't take ownership and will never attempt to delete the QString*. This raises the question as to why the parameter isn't declared as const QString*, but that's a whole other question.

I encourage you to write a unit test if you want a 100% guarantee. While extremely unlikely (this isn't PHP after all), it's just possible that the behaviour will change in a later version.

nephtes
  • 1,319
  • 9
  • 19
  • The reason it's not `const` is because `QTextStream` can write into it as well: `stream << 2; //the string will now contain "2"`. – coyotte508 Jun 09 '16 at 15:38
  • "This raises the question as to why the parameter isn't declared as const QString*" - because you may want to write to it. – Murphy Jun 09 '16 at 15:38
  • Ahh of course. Didn't realize it was a read-write container. Thanks. – nephtes Jun 09 '16 at 17:03