[Qt-interest] How to use a QObject tracking QWeakPointer (thread-)safely?
Stephen Kelly
steveire at gmail.com
Wed Dec 1 22:54:11 CET 2010
Hi,
QWeakPointer QObject tracking section has some cautions about tracking
objects in other threads. I should call data() only if I can guarantee the
contained pointer will never be deleted by another thread.
One way of providing that guarantee is to ensure that data() is only called
if the contained QObject has affinity to the currentThread().
How can I guarantee that? It seems like the only thing I can do is document
it?
For example, how can this get more safety than the apidox provides?
class MyClass
{
/**
@p object must have the same thread affinity as the instance of MyClass.
@p object must not be moved to another thread while this instance
of MyClass exists.
*/
void setObject(QObject *object)
{
Q_ASSERT(object ? object->thread() == QThread::currentThread() : true);
m_object = QWeakPointer(object);
}
void doSomething()
{
if (m_object) {
// The object tracked by m_object might be deleted in another thread
// at this point.
Q_ASSERT(m_object.data()->thread() == QThread::currentThread());
// Use m_object.data();
}
}
private:
QWeakPointer<QObject> m_object;
};
Thanks,
Steve.
More information about the Qt-interest-old
mailing list