Delete for std::future

Delete for std::future

本文关键字:future std for Delete      更新时间:2023-10-16

我正在动态创建线程:

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变量是我的类的静态成员。


假设如果我不删除该对象future则成本非常大(已经检索到的未来)

如果出于某种原因你确实需要指针,你不应该在向量中使用拥有原始指针。

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*/));

无论哪种方式,您都不需要手动循环并删除任何内容。

(也许在其他线程中,可能是其他一些功能)

如果您仍然使用原始指针,那么您确实需要更好地定义所有权策略。允许一些随机的其他代码删除它不拥有的资源不是一个好主意。