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.*/
});
You should make lambda state mutable:
auto thread = std::thread([uptr{ std::move(uptr) }]() mutable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With