首页 > 解决方案 > C++ 标准::未来在递归函数中

问题描述

考虑到以下情况,是否可以递归到函数中?我不认为 std::move 会起作用,因为展开变量会消失,你会如何处理这样的事情?

auto TestFunc(std::future<bool> promisedExit
        , int max
        , const char* pszTesting)
{
  if (promisedExit.get()) { // The calling thread will set this to cause this thread to exit.
     return false;
  }
  ...
  ...
  ...
  if (max != 10) {
     TestFunc(std::move(promisedExit), max++, pszTesting); // Issue is here with std::move(...)
  }
  ...
  ...
  ...
}

澄清一下,我不确定我是否可以在不移动的情况下传递未来?即让未来有效地检查每个递归?

标签: c++11promisestd

解决方案


使用 a shared_future,而不是 a (unique) future。你可以从你开始share()的开始得到第一个future

auto TestFunc(std::shared_future<bool> promisedExit
        , int max
        , const char* pszTesting)
{
  if (promisedExit.get()) { // The calling thread will set this to cause this thread to exit.
     return false;
  }
  ...
  ...
  ...
  if (max != 10) {
     TestFunc(promisedExit, max++, pszTesting);
  }
  ...
  ...
  ...
}

推荐阅读