简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM