开发者

Why doesn't the move constructor get called in the fill_n

The error I get says that the fill_n line below is trying to use the deleted copy constructor: why is it not trying to use the move constructor? I tried wrapping it in a std::move but that didn't help.

std::vector< std::thread > workers;
workers.reserve( 10 );
std::fill_n( std::back_inserter( workers ), 10, std::thread( []{ std::cout << "thread\n"; } ) );

However, if I change the fill_n line to

for( int i = 0; i < 10; ++i )
{
  workers.push_back( std::thread( []{ std::cout << "thread\n"; } ) );
}

that works fine. I thought开发者_如何学运维 these were essentially the same as I've done changes from the one to the other before in somewhat similar looking code.


On the line

std::fill_n( std::back_inserter( workers ), 10, std::thread( []{ std::cout << "thread\n"; } ) );

there is a single temporary std::thread instance created, and fill_n tries to make 10 copies of it to fill workers. You cannot move an object to make many copies - it just doesn't make any sense.

What you want is probably std::generate_n:

std::generate_n(std::back_inserter(workers), 10, [] {
    return std::thread([] { std::cout << "thread\n"; });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜