[Interest] Strange behaviour of QByteArray reserve/reallocation mechansim

Bo Thorsen bo at vikingsoft.eu
Mon Nov 10 09:24:09 CET 2014


Hi Bernhard,

Den 09-11-2014 kl. 10:34 skrev Bernhard:
> I just experienced a strange behavior of QByteArray regarding its internal
> reallocation behavior. Actually that behavior stops me from using
> capacity()/reserve() to optimize the allocation behavior and its seem to me
> that under current conditions reserve() is more or less useless. Using the
> current implementation there is no way of avoiding continuous reallocations
> while using QByteArray with data of different lengths.
>
> Please see the following SO post (please tell me if it is not allowed to
> post such links in this ML):
>
> http://stackoverflow.com/questions/26821207/internal-reallocation-behaviour-
> of-qbytearray-vs-reserve
>
> Is this actually desired behavior? Is it a bug?

Desired? No. Bug? Maybe.

It depends entirely on your definition on what reserve() should support. 
For example, if you do this:

QByteArray a, b;
a.reserve(1000);
a = b;

There's no way you will ever preserve the reserve(), because that would 
conflict with the implicit sharing.

So in your case you use another operator=. Should that work? Well, if it 
does I'm sure no one would object. But since another operator= can never 
hold the reserve() promise, I don't really see the point.

reserve() means you can write directly in the byte array data, and then 
it works. I'd suggest that you follow this rule. You can do this by 
working directly on the data() pointer.

Bo Thorsen,
Director, Viking Software.

-- 
Viking Software
Qt and C++ developers for hire
http://www.vikingsoft.eu



More information about the Interest mailing list