[Development] QString, QVariant and QSQLite

Giuseppe D'Angelo giuseppe.dangelo at kdab.com
Thu May 27 10:50:06 CEST 2021


On 26/05/2021 21:39, Alberto Mardegan wrote:
> 
> Now, I haven't dug very deep in QString and QVariant, I preferred to let
> the experts talk first :-) Does the code in the QSQLite plugin look
> correct to you?

That depends: when does SQLite exactly stop using the string data passed 
to it exactly?


> Is it expected that QString::utf16() makes a memory allocation? And is
> it correct that this happens even when the QString is const?

In the overwhelming majority of cases, utf16() won't make any 
allocation. There's just one exception -- if the QString was built via 
fromRawData(). In that case, in order to ensure NUL termination, utf16() 
does actually "detach" (even if it's a const method).

(Fun fact: utf16() is one of the few const methods in Qt value classes 
which isn't thread safe.)

It's a bit interesting that SQLite takes pointer+size, so does not seem 
to require NUL termination -- for that use case, there's 
unicode()/constData() + size(), that never reallocates (unlike utf16()).



> And why destroying a const QVariant causes the deallocation of the data
> created by QString::utf16()??

QString::utf16 doesn't "create" data: it modifies the string *itself* so 
that it becomes detached and NUL terminated. When you destroy that 
QString, you'll be deallocating the data (provided there are no more 
shallow copies around).

Similarly, when you destroy a QVariant, you destroy the object it's 
holding (provided there are no further shallow copies around).

So yes, in the general case, destroy QVariant -> destroy the QString 
contained -> deallocate memory.


HTH,
-- 
Giuseppe D'Angelo | giuseppe.dangelo at kdab.com | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - The Qt, C++ and OpenGL Experts

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4329 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://lists.qt-project.org/pipermail/development/attachments/20210527/2d832292/attachment-0001.bin>


More information about the Development mailing list