QCache和QSharedPointer [英] QCache and QSharedPointer
问题描述
问题是,我有 QVector
的 QSharedPointer
,我想把它们的一部分 QCache
。如何插入一个共享指针 QCache
?如果我将指针设置为我的缓存但是破坏了 QVector
和共享指针,会发生什么?将内存释放,我的缓存指向无处吗?
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?
推荐答案
这是一个错误,如果你只是一个指针指向你的项目 QChache
,同时这样的指针由 QSharedPointer
管理。 item对象可以被 QSharedPointer
析构函数销毁,因此 QChache
将有无效的指针。这是一个通用的问题,你不能有不同的指针的所有者不知道对方。如果你通过 QSharedPointer< Item>
管理指针,那么 QChache
不能直接使用 / code>,它只能与
QSharedPointer< Item>
配合使用,例如:
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)));
因此, QCache
应该有自己的副本的动态分配 QSharedPointer
对象和 QSharedPointer
对象应该正确初始化其他 QSharedPointer
已拥有
Item
实例的所有权。
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.
这篇关于QCache和QSharedPointer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!