Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QCache and QSharedPointer

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?

like image 587
adapto Avatar asked Sep 12 '25 22:09

adapto


1 Answers

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.

like image 198
Orest Hera Avatar answered Sep 14 '25 12:09

Orest Hera