从不从 std::packaged_task 检索 std::future 的结果是否安全?

Is it safe to never retrieve the result of a std::future from a std::packaged_task?

std::packaged_task 创建 std::future 是否安全,它在单独的线程上执行,但并不总是检索其结果?

#include <future>
#include <thread>

class Result {
  Result() {}
  ~Result() {}
};

void foo() {
  std::packaged_task<Result()> task(..);
  auto future = task.get_future();
  std::thread thread(std::move(task), ...);
  thread.detach();
  if (future.wait_for(std::chrono::milliseconds(timeout_ms)) == std::future_status::ready) {
    auto result = future.get();  <--- Task didn't take too long, retrieve future result
    ...
  }
}  <--- Task is taking too long, just abort and never call future.get()

它似乎在 Clang / libc++ 上工作:~Result()std::packaged_task 调用返回的结果,无论是否 get() 最终被调用 std::future , 但由于我在 C++ 文档中找不到有关此使用模式的任何内容,我想确保它得到官方支持。

这取决于....您认为对您的程序来说什么是安全的。
对于您显示的上下文,它是安全的:

  • 在对 future 执行 get 之前销毁 future 时不会阻塞。如果 future 是使用 std::async 创建的,并且如果你在它被销毁之前没有调用 get ,它会一直阻塞直到结果可用。
    在此处查看更多信息:http://en.cppreference.com/w/cpp/thread/future/~future

these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state.

现在,如果 Result class 持有非拥有内存(无论出于何种原因)或其他需要手动释放的资源怎么办。在这种情况下,您的代码的正确性就会受到质疑。更好的做法是将其分派到某个后台线程以执行缓慢移动的任务。