QCache and QSharedPointer

 ̄綄美尐妖づ 提交于 2019-12-10 10:25:58

问题


The problem is, that I have a QVector of QSharedPointer and I want to put part of them to my QCache. How can I insert a shared pointer to QCache? What happens if I set the pointer to my cache but destroy the QVector and the shared pointer in it? Will the memory be released and my cache points to nowhere?


回答1:


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.



来源:https://stackoverflow.com/questions/33280524/qcache-and-qsharedpointer

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