LearnFrenzy
Sign in Take a free test

Multithreading · Find the Error · Question 7

Error: copying a std::future Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <future>
#include <iostream>

int main() {
    std::future<int> f = std::async([] { return 7; });
    std::future<int> g = f;
    std::cout << g.get() << '\n';
    return 0;
}
  • A async needs a launch policy
  • B std::future is move-only (its result can be taken once); move it, or call f.share() to get a copyable std::shared_future Correct
  • C get must be called on f
  • D Lambdas cannot be async
Correct Answer: Option B

shared_future allows several threads to wait for the same result.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links