LearnFrenzy
Sign in Take a free test

Move Semantics · Find the Error · Question 10

Error: copying a lambda that holds a moved-in unique_ptr Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

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

main.cpp
#include <functional>
#include <iostream>
#include <memory>

int main() {
    auto p = std::make_unique<int>(5);
    auto task = [q = std::move(p)] { return *q; };
    std::function<int()> f = task;
    std::cout << f() << '\n';
    return 0;
}
  • A Init captures cannot move
  • B The lambda owns a unique_ptr, so it is move-only, but std::function requires a copyable callable; use std::move_only_function (C++23) or call task directly Correct
  • C f must be auto
  • D *q is invalid
Correct Answer: Option B

Moving the lambda into std::function would not help either – std::function itself must be copyable.

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