【问题标题】:How to delete object through it's pointer stored in std::list?如何通过存储在std :: list中的指针删除对象?
【发布时间】:2018-06-05 11:51:08
【问题描述】:

我正在使用 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 对象的空间?

【问题讨论】:

  • 通常在线程上有一个join()detach() 方法。检查文档。此外,您可能希望将其存储在 std::unique_ptr 中,以便在不再引用它时进行清理。

标签: c++ multithreading poco


【解决方案1】:

处理这个问题的最好方法是使用智能指针 喜欢std::unique_ptr

你还必须在调用他的析构函数之前在你的线程上调用joindetach

假设 c++11 和 #include &lt;memory&gt;

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);
          }
     }

【讨论】:

  • 你所说的“需要加入或分离线程才能使加入”是什么意思?你能解释更多或提供一些代码吗?
  • 我认为你的意思是线程不能连接——你必须在线程上调用join(),或者在销毁它之前调用detach(),这两者都会使joinable()返回false。参见 libstdc++ 中的 std::thread 的析构函数:github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/…
  • @PaulBelanger:您的评论似乎基于 std::thread,但 OP 说他使用的是 Poco::Thread,这有点不同(例如,我不相信它有 @987654333完全是@)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
相关资源
最近更新 更多