Visual c ++ why std :: move crash

I want to add a vector to the end of another vector. To my knowledge, the std::move() function is the "selection function" for this task. Why is std::move() from Microsoft Visual C ++ Express crashing while the manually processed loop works as expected?

I am using Microsoft Visual C ++ 2015 update 3. Unfortunately, I cannot verify this with other compilers.

 // The setup code for the two vectors: vector<unique_ptr<channel>> channels, added_channels; // ... here is some code that adds some elements to both vectors 

To my knowledge, the following two parts of the code should work the same. They must move the added_channels elements to the end of the channels .

This is the first option that crashes:

 std::move(added_channels.begin(), added_channels.end(), channels.end()); 

This is the second version that works:

 for(auto & ref : added_channels) { channels.push_back(std::move(ref)); } 
+5
source share
2 answers

This is actually one of the few cases where a move_iterator really useful:

 channels.insert(channels.end(), std::make_move_iterator(added_channels.begin()), std::make_move_iterator(added_channels.end())); 

For insertion into a vector the insert range is preferable to a phased push_back (or equivalent back_inserter ), since it avoids unnecessary redistributions and expands the storage correctly. The latter is easy to spoil: the indiscriminate use of reserve can easily cause quadratic behavior.

+3
source

std :: move moves to a specific location.
If you want to insert it in the back of the vector, you should use std :: back_inserter

 std::move(added_channels.begin(), added_channels.end(), std::back_inserter(channels)); 
+12
source

Source: https://habr.com/ru/post/1274861/


All Articles