cube
cube

Reputation: 3938

The right way of using QIODevice::readLine()

I'm trying to use QIODevice::readLine(). I have looked at the two versions -- one returning QByteArray:

QByteArray buffer = iodevice->readLine()

and one reading to char* buffer:

char buffer[SIZE];
qint64 used;
used = iodevice->readline(buffer, SIZE);

I need to read a line, detect errors and manipulate it as QString.

Which of these two overloaded versions should I use to make it simple and efficient?

What I know so far:

Upvotes: 2

Views: 2236

Answers (1)

Luca Carlon
Luca Carlon

Reputation: 9986

There is no better way, it depends on the application I guess. You can simply profile the two if performance of this operation is critical for your application.

Consider that by using the QByteArray you're not allocating the memory "back and forth". QByteArray implements implicit sharing, so it is fast and efficient to use the operator =. Exactly the same as the char*, but simpler maybe.

QString has both the ctor with the QByteArray and the char*, so that is exactly the same.

EDIT: To clarify the point about copies when QByteArray is returned by value consider that yes, two objects might be created, but only shallow copies are made. This is therefore efficient. You might want to read this which is very important. Also, consider having a closer look :-)

Upvotes: 2

Related Questions