'Moving unique_ptr inside a lambda function gives me a compiler error on C++17 [duplicate]

Given the following hierarchy:

class IJobInterface
{
};

class JobAbstract : public IJobInterface
{
public:
    JobAbstract(std::string n) : name(n) {};

protected:
    std::string name;
};

class JobConcrete: public JobAbstract
{
public: 
    JobConcrete(std::string n, int i) : JobAbstract(n), index(i) {};
    void doIt();

private:
    int index;
};

When I need to pass JobConcrete as unique_ptr param inside a lambda function:

void doSomenthigHeavy(std::unique_ptr<JobConcrete> j)
{
    j->doIt();
}

void main()
{
    auto job = std::make_unique<JobConcrete>("name", 0);
    doSomenthigHeavy(std::move(job)); //it works

    auto t = std::thread([j = std::move(job)]
    {
        doSomenthigHeavy(std::move(j)); //it doesn't work
    });
}

Then I get a compiler error: enter image description here

The question is: what am I missing here? Calling doSomenthigHeavy from inside a lambda produces a compiler error while from outside it doesn't.



Solution 1:[1]

The issue is that lambda's operator () is declared const and with the move you try to modify the unique pointer j.

Declare it mutable via auto t = std::thread([j = std::move(job)]() mutable ...) or pass the unique_ptr as an argument to the lambda.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ALX23z