简体   繁体   中英

How to delete object through it's pointer stored in std::list?

I am using Poco::Thread.

 std::list<Thread*> threads;
    for(int i=0;i<100;i++){
       Thread* t=new Thread();
       RunnableClient* r=new RunnableClient(); //this class has run method()
       threads.push_back(t);
       t.start(*r);
    }
    std::list<Thread*>::iterator it;
    for (it = threads.begin(); it != threads.end(); ++it){
       if((*it)->isRunning() == false){
          threads.erase(it,it);
          }
     }

erase() method used in the above function just removes the reference to the object, but does not free up the space allocated to the Thread objects. How to free the space allocated to the Thread objects ?

the best way to handle this is to use smart pointer like std::unique_ptr

also you must call join or detach on your thread before his destructor is called

asumming c++11 and #include <memory>

std::list<std::unique_ptr<Thread> > threads;
    for(int i=0;i<100;i++){
       RunnableClient* r=new RunnableClient(); //this class has run method()
       threads.emplace_back(std::make_unique<Thread>());
       threads.back().start(*r);
    }
    //need to join or detatch thread before destoying them
    std::list<std::unique_ptr<Thread> >::iterator it;
    for (it = threads.begin(); it != threads.end(); ++it){
       if((*it)->isRunning() == false){
          threads.erase(it,it);
          }
     }

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