我可以从基于范围的元素中移动元素吗?

YiF*_*Fei 5 c++ move c++11

假设我有一些像这样的代码:

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
}
Run Code Online (Sandbox Code Playgroud)

我只是想知道编译器(我可能使用VS2015或gcc 6)是否可以优化以将元素移动到for循环中.或者我该怎么做才能让它进入,因为字符串可能非常冗长.

一个老人会开始为循环或协程提供帮助吗?

Sla*_*ica 6

如果你想从矢量移动元素来some_function()只是做move明确的:

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


for(auto &i:produce(str))
    some_function( std::move(i) );
Run Code Online (Sandbox Code Playgroud)

否则,将元素移动到for循环中并不清​​楚你的意思.