[Interest] Strange behaviour of QByteArray reserve/reallocation mechansim

Alejandro Exojo suy at badopi.org
Wed Nov 12 09:22:16 CET 2014


El Monday 10 November 2014, Bernhard escribió:
> So after all I am not supposed to use clear() or operator=() after calling
> reserve()? That should be documented. Without that knowledge it obviously
> is impossible to use reserve() in a sensible way.

There was a similar question on the development mailing list about clearing 
QVector while keeping the capacity. The solution seems to use erase(), and 
that is not available on QByteArray, but see below.

http://lists.qt-project.org/pipermail/development/2014-November/019015.html

> If you don't have an idea how that could be improved on the code side I
> would file a suggestion about extending the documentation a bit.

I think that this will work for you (if I understood your use case):

    QByteArray buffer;
    buffer.reserve(1000);
    buffer.append("foo");
    qDebug() << "buffer" << buffer.capacity() << buffer;

    buffer.truncate(0);
    buffer.append("bar");
    qDebug() << "buffer" << buffer.capacity() << buffer;

This prints:

buffer 1000 "foo"
buffer 1000 "bar"

As Bo explained, operator= doesn't work because of the implicit sharing. It 
can be tricky to document which member functions will hold the reserved memory 
without adding lots of noise to each member description. Maybe the Qt 
developers don't even want to commit to keeping the same behaviour during all 
the Qt5 timespan.

Sending a patch to improve the documentation is easy once you do the initial 
procedure:

http://qt-project.org/wiki/Qt-Contribution-Guidelines

-- 
Alex (a.k.a. suy) | GPG ID 0x0B8B0BC2
http://barnacity.net/ | http://disperso.net



More information about the Interest mailing list