我正在使用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()方法只是删除了对象的引用,但是没有释放分配给Thread对象的空间。如何释放分配给Thread对象的空间?
答案 0 :(得分:2)
处理此问题的最佳方法是使用智能指针
比如std::unique_ptr
你也必须在调用析构函数之前调用线程上的join
或detach
asumming c ++ 11和#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);
}
}