Home > OS >  is it safe to use std::move_iterator in std algorithm with lambda as pred
is it safe to use std::move_iterator in std algorithm with lambda as pred

Time:07-02

std::vector<std::string> foo{"a","b","c"};
std::set<std::string> check{"a"};
std::vector<std::string> bar{"something_here"};
typedef std::vector<std::string>::iterator Iter;

std::copy_if(std::move_iterator<Iter>(foo.begin()), std::move_iterator<Iter>(foo.end()), std::back_inserter(bar),
[&check](std::string && s)->bool{return check.find(s) == check.end();});

When I tested above code everything works but I am not sure why.
My assumption was (likely wrong), in each "std::copy iteration", doesnt each string in foo gets "moved" into the lambda and when lambda returns, every variable(except captures) inside the lambda definition should go out of scope? Since the string was moved inside the lambda, why doesnt that invalidate whats been inserted into bar?

Test link (https://onecompiler.com/cpp/3y8qeeqqr)

Edit: Is it because although string is passed into lambda as rvalue, it was not used to construct another string, so effectively the input string was not "moved", i.e., ownership of that string resource is unchanged?

CodePudding user response:

Is it because although string is passed into lambda as rvalue, it was not used to construct another string, so effectively the input string was not "moved", i.e., ownership of that string resource is unchanged?

Yes. Simply forming an rvalue reference does not modify an object. The object doesn't even know it happened. Since your only use of the string in the lambda is reading it, its value is not changed.

  • Related