2
votes

I'm very new to C++ in general, and to Qt as well, thus I have a question:

I've got this code:

if(!logFile.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", logFile.errorString());
}
else {
    QTextStream result(&logFile);
    return result.readAll();
}

It is running fine. However, when I try to return the QTextStream object instead of QString w/ all the text I've read from file, following error pops up:

/home/neko/projects/WurmLogparser/wurmlog.cpp:208: error: call to deleted constructor of 'QTextStream'
        return result;
               ^~~~~~

code what is causing error seen below:

else {
    QTextStream result(&logFile);
    return result;
    //return result.readAll();
}

Of course, I'm changing the related types to QTextStream appropriatelly before trying to compile second version. Please, tell me what is the problem with 2nd version of code? I construct QTextStream the same way as in the first part, but it produces strange error for me.

2

2 Answers

4
votes

TextStream object [...] w/ all the text

The stream does not "contain" any text. It is a means of retrieving the text from a QIODevice, but by itself it doesn't contain the text.

Returning a string was the right thing to do in your case.

QTextStream is non-copyable. You can't return it by value. In most cases, it makes no sense to return such an object. If you're operating on a stream, you should pass it as a reference parameter:

void myFunction(QTextStream & stream) { ... }

If you wish to return the contents read from a file, you can return them as a string (as you did), or as raw binary data:

QByteArray myFunction() {
  ...
  return logFile.readAll();
}

You can then use a stream on the byte array:

void foo() {
  auto data = myFunction();
  auto stream = QTextStream(&data);
  // use the stream
  ...
}
1
votes

Just to further clarify, the copy constructor for QTextStream (and also the = operator) are both private, this is the reason that you can't copy them :o

Methods to get around that are explained well by Kuba (+1 :)