QCache and QSharedPointer

会有一股神秘感。 提交于 2019-12-05 18:29:42

It is a bug if you put just a pointer to your item to QChache and at the same time such pointer is managed by QSharedPointer. The item object can be destroyed by QSharedPointer destructor, so QChache will have invalid pointer. It is a generic issue that you cannot have different owners of a pointer that do not know each other. If you manage pointers by QSharedPointer<Item> then QChache should not work directly with Item it should work only with QSharedPointer<Item>, for example:

// wrong
QCache<int, Item> cache;
QVector<QSharedPointer<Item> > vec;
Item *item = new Item;
vec.push_back(QSharedPointer<Item>(item));
cache.insert(1, item);
// or
cache.insert(1, vec.at(0).data());

// also wrong
QCache<int, <QSharedPointer<Item> > cache;
vec.push_back(QSharedPointer<Item>(item));
cache.insert(1, new QSharedPointer<Item>(item));
// here two different instances of QSharedPointer are initialized
// by the same pointer 'item'

// correct
QCache<int, <QSharedPointer<Item> > cache;
cache.insert(1, new QSharedPointer<Item>(vec.at(0)));

So, QCache should have its own copy of dynamically allocated QSharedPointer object and that QSharedPointer object should be correctly initialized by other QSharedPointer that already has ownership of the Item instance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!