简体   繁体   中英

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. 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.

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.

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. You can solve this wrapping the reference with std::ref .

In this case I think to use a std::shared_ptr is the best way.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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