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.