Question 7
Back to Exercise
What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)
#include <future>
#include <iostream>
#include <stdexcept>
#include <vector>
int parse(int v) {
if (v < 0) throw std::invalid_argument("negative input " + std::to_string(v));
return v * 2;
}
int main() {
std::vector<std::future<int>> fs;
for (int v : {4, -1, 6}) fs.push_back(std::async(std::launch::async, parse, v));
int ok = 0;
for (auto& f : fs) {
try { ok += f.get(); }
catch (const std::exception& e) { std::cout << e.what() << ' '; }
}
std::cout << ok << '\n';
return 0;
}
- A negative input -1 20 Correct
- B 20
- C The program terminates
- D negative input -1 18
Correct Answer: Option A
The task's exception is stored in its future and rethrown by get() in the main thread; the other tasks still give 8 and 12.
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!