Why local variables in the lambda object are const?

Viewed 405

Following code doesn't compile. Because pt has type of const std::packaged_task<void()>> and operator() is not const.

auto packagedTask = std::packaged_task<void()>>([]{});
auto future = packagedTask.get_future();
auto function = [pt = std::move(packagedTask)]{ (*pt)(); });

Here is workaround:

auto packagedTask = std::make_shared<std::packaged_task<void()>>([]{});
auto future = packagedTask->get_future();
auto function = [pt = std::move(packagedTask)]{ (*pt)(); });

Why local variables in the lambda object are const? I want to make first code work without overheads to workarounds. What is best practice to solve the issue?

1 Answers
Related