[Qt-interest] On overriding qMalloc in QVector

Benoit Jacob jacob.benoit.1 at gmail.com
Thu Oct 22 22:05:05 CEST 2009


2009/10/22 Benoit Jacob <jacob.benoit.1 at gmail.com>:
> 2009/10/22 Thiago Macieira <thiago at kde.org>:
>> Em Quinta-feira 22 Outubro 2009, às 20:01:29, você escreveu:
>>> > I managed to get an aligned QVector data, but the change is not data-
>>> > compatible.
>>>
>>> ah ok.
>>>
>>> > If I put this change in Qt 4.6, then we could have newly-compiled code
>>> > allocating aligned buffers passing a QVector to code that wasn't
>>> > recompiled. If that older code tried to free the vector, the application
>>> > would most likely crash.
>>> >
>>> > I think I can safely make the change for QMap and QHash though. QList
>>> > isn't affected by this issue, while QLinkedList cannot be solved properly
>>> > (it uses new on QLinkedListNode<T>).
>>>
>>> hm, since this can't be done for QVector, i'd say don't bother. it
>>> would only make things more complicated.
>>>
>>
>> After a bit more of experimentation, I think it can be done.
>>
>> I'm just using a bit of heuristics: if the type alignment is less than a
>> certain threshold, continue using qMalloc and qFree. Otherwise, use the
>> aligned functions. The idea is that, if the alignment requirement was higher
>> than what qMalloc returned, then no one was using QVector with that type.
>
> Sure that logic seems correct, but i don't understand, how do you get
> the type alignment? Some compiler extensions? The alignof keyword is
> only coming in c++1x...

Ah, one solution would be to put



template<typename T>
struct qt_type_alignment
{
  enum { ret = 0 }; // 0 means default alignment
};

#define Q_DECLARE_TYPE_ALIGNMENT(type,alignment) \
template<> \
struct qt_type_alignment<type> \
{ \
  enum { ret = alignment }; \
};



in, say, qglobal.h, and then tell the user that if (s)he wants to use
QVector on an aligned type, he just needs to first #include QVector
and do, e.g. Q_DECLARE_TYPE_ALIGNMENT(mytype,myalignment).

Inconvenient: not an automatic solution as you were proposing (still
don't know how you could implement that)
Advantage: guarantees it won't disturb existing code, as it's completely opt-in

Benoit




More information about the Qt-interest-old mailing list