0

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.

anc
  • 106
  • 4
  • 18

1 Answers1

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.

ALX23z
  • 4,456
  • 1
  • 11
  • 18