initialization order of lambda as parameter which accepts other parameters

Viewed 44

I have a parameter (in this case std::vector) that I need to pass to an async method (preferably by move) and to a callback lambda. Does the approach below guarantee that the lambda will be initialized first (implying vector being copied) so that I can move the vector to the async method?

Method(std::vector<std::string> vec)
{
    AsyncMethod(std::move(vec), [vec]() 
    {
        // act on vec
    });
}
1 Answers

The order of evaluation of function parameter is unspecified, hence you can't rely on your assumption. A solution would be the following.

Method(std::vector<std::string> vec)
{
    auto l = [vec]() { /* Act on vec... */ };

    AsyncMethod(std::move(vec), l);
}

Depending on the signature of AsyncMethod, you might even want to pass the lambda as std::move(l). This would again be safe, as the vector has been copied into the closure beforehand.

Related