gpt4 book ai didi

c++ - 如何通过存储在 std::list 中的指针删除对象?

转载 作者:行者123 更新时间:2023-11-28 01:33:09 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于c++ - 如何通过存储在 std::list 中的指针删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50699406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com