QCache and QSharedPointer

2019-07-03 16:38发布

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条回答
姐就是有狂的资本
2楼-- · 2019-07-03 17:19

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.

查看更多
登录 后发表回答