Eric
Eric

Reputation: 1

Forward std::unique_ptr via lambda into a function

I have an class job. I want to create a unique_ptr of job, capture it in a lamdba and execute a function in a lambda which forwards this pointer:

The function:

void printJob(std::unique_ptr<job> aJob)

Lamdba:

auto jobptr = std::make_unique<job>(<arguments>);

auto function = [this, j = std::move(jobptr)]
{
    printJob(j);
};

The function is executed on a different thread therefor the lamdba is used The j argument in the lamdba is of type std::remove_reference_t<std::unique_ptr<job> &> while the function need a std::unique_ptr<job>. Can I make this work? Tried options with std::move and std::forward but I cant get it to compile. I am using C++14.

I have found alternatives (shared_ptr, raw pointer, etc) but this is more in sync with the existing code.

Upvotes: 0

Views: 432

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

If printJob's parameter is a std::unique_ptr<job> then it must be passed in via move semantics, via std::move itself.

Captured objects in regular lambdas are, effectively, const object, hence they are not movable. The solution is simple: use a mutable lambda.

auto function = [this, j = std::move(jobptr)]
mutable {
    printJob(std::move(j));
};

It goes without saying that this lambda can only be effectively executed just once.

But does printJob really need to take ownership of the passed in parameter? If not, if it's just as happy as

void printJob(const std::unique_ptr<job> &aJob)

then none of this is needed.

Upvotes: 1

Related Questions