如何清理复杂的QList?
我在 QAbstractTableModel 的派生中使用相当复杂的 QList 来存储数据:
class MyTableModel : public QAbstractTableModel {
Q_OBJECT
QList<QHash<int, QHash<int, QVariant> *> *> m_data;
/*...*/
};
MyTableModel::~TMusicTableModel() {
/* Should I deallocate QList items? */
}
MyTableModel::setData(int row, int col, int type, QVariant value) {
/* inserting a new data field */
QHash<int, QHash<int, QVariant> *> *row_hash = new QHash<int, QHash<int, QVariant> *>();
QHash<int, QVariant> *role_hash = new QHash<int, QVariant>();
type_hash->insert(type, value);
row_hash->insert(col, type_hash);
m_data.insert(row, row_hash);
return true;
}
我想知道 QList 和 QHashes 是否负责处理交易,或者我是否应该这样做。 在这种情况下,文档提供的信息并不多。
I'm using a rather complex QList in a derivation of QAbstractTableModel to store data:
class MyTableModel : public QAbstractTableModel {
Q_OBJECT
QList<QHash<int, QHash<int, QVariant> *> *> m_data;
/*...*/
};
MyTableModel::~TMusicTableModel() {
/* Should I deallocate QList items? */
}
MyTableModel::setData(int row, int col, int type, QVariant value) {
/* inserting a new data field */
QHash<int, QHash<int, QVariant> *> *row_hash = new QHash<int, QHash<int, QVariant> *>();
QHash<int, QVariant> *role_hash = new QHash<int, QVariant>();
type_hash->insert(type, value);
row_hash->insert(col, type_hash);
m_data.insert(row, row_hash);
return true;
}
I'm wondering if the QList and QHashes take care of the deallaction or if I should do it. The documentation is not very informative in this case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为您正在使用“new”创建子项,所以您必须自己取消分配它们。 有关执行此操作的快速方法,请参阅 qDeleteAll 函数。
您使用 new 创建这些哈希有什么原因吗? (您的代码显然只是一个片段,因此可以在其他地方使用和传递指针。)通常,在堆栈上构造它们以便自动发生销毁要简单得多。
Because you're creating the sub items with "new", you do have to deallocate them yourself. See the qDeleteAll function for a quick way of doing so.
Is there a reason why you're using new to create these hashs? (Your code is obviously just a snippet, so the pointers could be used and passed around elsewhere.) Generally, it's much simpler to just construct them on the stack so that destruction happens automatically.
与几乎所有 C++ 库中的任何其他容器类一样,解构它也会激活其中元素的析构函数。 对于简单的
MyClass array[3]
、STLvector
以及 QT 的QList
都是如此。< br>为了确保所有内容都被销毁,您需要确保 MyClass 有一个析构函数,确实可以释放所有资源。 拥有指针的 QList 并不遵循此规则,因为指针没有析构函数。 相反,您可能想使用 boost 的shared_ptr 或编写您自己的智能指针包装器。
Like any other container class in practically any C++ library, destructing it also activates the destructor of the elements in it. this is true for a simple
MyClass array[3]
, for STLvector<MyClass>
and for QT'sQList<MyClass>
as well.To make sure everything is destroyed you need to make sure that MyClass has a destructor that indeed deallocates all the resources. Having a QList of pointers does not follow this rule because pointers don't have destructors. instead you may want to use boost's shared_ptr or write your own smart pointer wrapper.