我正在动态创建线程:
auto thr =new std::future<void>(std::async(/*some callable*/));
我将所有这些指针存储在 std::vector<future<void>*>
中.为了释放内存,我正在这样做:
for(int i(0);i<futureVector.size();i++)
{
if(futureVector.at(i)->valid())
{
futureVector.at(i)->get(); // for getting exception,if any
}
delete futureVector.at(i); // the problem is here
}
现在在我的代码中,可能会发生为 futureVector.at(i)
分配的内存已经被释放(可能在其他线程中,可能是通过其他函数)。
我的问题是如何检测 futureVector.at(i)
处的指针是否有效?我的意思是它指向一个有效的 std::future
还是不是?
注:futureVector
变量是我类(class)的静态成员。
假设我不删除那个future
object 是代价非常大的(已经取回的 future)
最佳答案
如果出于某种原因您确实需要指针,则不应在 vector 中使用拥有原始指针。
auto thr = std::make_unique<std::future<void>>(std::async(/*some callable*/)); // C++14
std::unique_ptr<std::future<void>> thr {new auto {std::async(/*some callable*/)}; // C++11
但实际上您可能根本不需要指针。仅仅因为您不知道要创建多少个线程并不意味着您需要使用指针。
std::vector<std::future<void>> futureVector;
futureVector.emplace_back(std::async(/*some callable*/));
无论哪种方式,您都不需要手动循环并删除任何内容。
(maybe in some other thread, may beby some other function)
如果您仍然使用原始指针,那么您确实需要更好地定义所有权策略。允许一些随机的其他代码删除不属于它的资源不是一个好主意。
关于c++ - 为 std::future 删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767449/