Delete for std::future
Delete for std::future
我正在动态创建线程:
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*/));
无论哪种方式,您都不需要手动循环并删除任何内容。
(也许在其他线程中,可能是其他一些功能)
如果您仍然使用原始指针,那么您确实需要更好地定义所有权策略。允许一些随机的其他代码删除它不拥有的资源不是一个好主意。
相关文章:
- 架构决策:返回std::future还是提供回调
- std::p romise::set_value() 和 std::future::wait() 是否提供内存围栏?
- 修改在 std::future 的 lambda 中引用捕获的值
- 从 T 创建 std::future 的最佳方式<T>
- C++ std::future没有被调用
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- 如何使用 boost::future 重新抛出 std::exception_ptr 存储的原始异常?
- Make zmqpp::socket::connect a std::future
- std::future可以比std::promise活得更长吗
- std::future::get()或std::future::wait()是std::thread::join()的替
- 当 std::future 准备好被检索时发出信号主线程
- C++ std::future 方法应该<T>命名为 is_ready() 还是 ready()?
- 当多次调用时,"std::future::then"的行为是什么?
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- 使用 std::future 的不完整类型无效使用
- 为什么 std::future::wait_for 的行为不符合预期?
- 是什么给了 std::future 一些共享状态
- STD :: Future no_state异常与断言
- std::future<nboth:::Both<int, std::string>> 分段错误
- Using std::future/std::async