Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++14

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?

like image 792
Violet Giraffe Avatar asked Jul 31 '18 08:07

Violet Giraffe


2 Answers

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.*/
 });
like image 170
lubgr Avatar answered Nov 18 '22 04:11

lubgr


You should make lambda state mutable:

auto thread = std::thread([uptr{ std::move(uptr) }]() mutable
like image 5
user7860670 Avatar answered Nov 18 '22 04:11

user7860670