Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I move elements from a range-based for?

Tags:

c++

c++11

move

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?

like image 459
YiFei Avatar asked Nov 18 '16 03:11

YiFei


1 Answers

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.

like image 102
Slava Avatar answered Oct 26 '22 06:10

Slava