Cannot std::move from lambda capture to function call inside lambda, why?

  • A+
Category:Languages

In the following code

#include <memory> #include <thread> #include <utility>  void f1(std::unique_ptr<int>&& uptr) {}  void f(std::unique_ptr<int>&& uptr) {     auto thread = std::thread([uptr{ std::move(uptr) }]() {         f1(std::move(uptr));     }); }  int main() {     return 0; } 

the call to std::move inside the lambda cannot be compiled:

[x86-64 gcc 8.1 #1] error: binding reference of type'std::unique_ptr<int>&&' to 'std::remove_reference<const> std::unique_ptr<int>&>::type' {aka 'const std::unique_ptr<int>'} discards qualifiers 

Live demo: https://godbolt.org/g/9dQhEX

Why does this error occur and how can I fix it? Where does const come from?

 


You need to make the lamdba mutable as the closure variables are const-qualified by default.

auto thread = std::thread([uptr{ std::move(uptr) }]() mutable {                                                     //^^^^^^       f1(std::move(uptr)); /* Works, no constness-violation.*/  }); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: