Why are local variables in a lambda object const?

The following code will not compile. Since it pt

is of type const std::packaged_task<void()>>

and operator()

not const

.

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

      

Here's a 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 a lambda object const

? I want the first code to work without the overhead of workarounds. What is the best practice for solving the problem?

+3


source to share


1 answer


If the lambda is marked as mutable

, the generated one lambda::operator()

will qualify as const

. Marking your lambda as will mutable

prevent this behavior:

auto function = [pt = std::move(packagedTask)]() mutable { (*pt)(); });

      


Why local variables in a lambda object const

?



Local variables in closures generated by lambda expressions are not const

. This is the generated lambda::operator()

one that qualifies as const

. The best question is, "Why is the lambda operator()

implicit const

?

This is because the const

default is better than mutable

. Mutability introduces complexity. Immutability makes the code easier to understand.

const

should be the default default for the entire language, but this cannot be changed due to retro compatibility. Since lambdas were a completely new feature, the committee decided to go with const

default and optional mutability.

+6


source







All Articles