LearnFrenzy
Sign in Take a free test

Multithreading · Find the Error · Question 1

Error: thread argument for a reference parameter Answer, explanation & discussion

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

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

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

void fill(int& out) { out = 42; }

int main() {
    int result = 0;
    std::thread t(fill, result);
    t.join();
    std::cout << result << '\n';
    return 0;
}
  • A fill must return int
  • B std::thread copies its arguments and passes the copies as rvalues, which cannot bind to int&; pass std::ref(result) Correct
  • C result must be atomic
  • D join must be called before
Correct Answer: Option B

The compile error protects you from silently writing to a temporary copy.

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