YiFei YiFei - 18 days ago 5
C++ Question

Can I move elements from a range-based for?

Suppose I have some code like this:

std::vector<std::string> produce(const std::string& str){
// create a vector based on input
}

void consume(const std::string& str){
for (auto i:produce(str))
// do some thing that use the str
// and I'd like to move it from the vector
some_process(str) // for example, move into this function
}


I just wonder if the compiler (I may use either VS2015 or gcc 6) can optimize to move the elements into for-loop. Or what should I do to make it move in, since the string can be quite lengthy.

Would an old begin to end for loop or a coroutine help?

Answer

If you want to move elements from that vector to some_function() just do move explicitly:

void some_function( std::string str );
void some_function( std::string &&str ); // or explicitly


for(auto &i:produce(str))
    some_function( std::move(i) );

otherwise it is not clear what you mean by moving elements into for loop.