简体   繁体   English

清理一堆指针

[英]Cleaning up a stack of pointers

I'm having a few problem with cleaning a stack of pointers. 我在清理一堆指针时遇到一些问题。 In the below the line with the delete crashes: "memory fault/segmentation fault". 在下面带有删除的行崩溃:“内存故障/分段故障”。

std::stack<reports*> stack;
while(db.fetch())
{
    reports* report = new report(db);
    QThreadPool::globalInstance()->start(report);
    stack.push(report);
}
while( QThreadPool::globalInstance()->activateThreadCount() != 0 );

while( !stack.empty() )
{
    delete stack.top();
    stack.pop();
}

The context of this code is I think not relevant. 我认为此代码的上下文不相关。 Except that: db is passed by reference to report constructor, which immediately copy the necessary current row data as non pointer members. 区别在于:db通过引用传递给报表构造函数,报表构造函数立即将必需的当前行数据复制为非指针成员。 Can somebody give me a hint ? 有人可以给我提示吗?

EDIT: 编辑:

Self answer: 自我回答:

Ok I was touch by god lights just after writing my question. 好吧,写完我的问题后,我被上帝的光芒打动了。

by default 默认

QThreadPool::globalInstance()->start(report);

will take ownership of the object. 将获得对象的所有权。 Adding the following line in the loop solves the problem: 在循环中添加以下行即可解决此问题:

report->setAutoDelete(false);

Or symply not cleaning up... myself and let Qt Do it. 或暗示不清理...我自己,让Qt做。

Ok I was touch by god lights just after writing my question. 好吧,写完我的问题后,我被上帝的光芒打动了。

by default 默认

QThreadPool::globalInstance()->start(report);

will take ownership of the object. 将获得对象的所有权。 Adding the following line in the loop solves the problem: 在循环中添加以下行即可解决此问题:

report->setAutoDelete(false);

Or symply not cleaning up... myself and let Qt Do it. 或暗示不清理...我自己,让Qt做。

You could do two things to avoid the explicit memory magnament, and solve your problems: 您可以做两件事来避免显式的内存混乱,并解决您的问题:

  • Use smart pointers . 使用智能指针
  • Use references. 使用参考。 In the case of the stack, one of the requeriments of STL containers is that the elements must be copyable. 对于堆栈,STL容器的要求之一是元素必须是可复制的。 You can solve this wrapping the reference with std::ref . 您可以使用std :: ref解决这个包装引用的问题

In this case I think to use a std::shared_ptr is the best way. 在这种情况下,我认为使用std :: shared_ptr是最好的方法。

I think we would need to see the report class, obviously you are handling well the stack so the problem must be at the report (stacks top) when you try to delete them. 我认为我们需要查看报告类,显然您的堆栈处理得很好,因此,当您尝试删除它们时,问题必须出在报告(堆栈顶部)。

Check/create the report destructor, there must be something that you might handle there too 检查/创建报告析构函数,那里也必须有一些您可以处理的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM