简体   繁体   中英

visual c++ why does std::move crash

I want to append a vector to the end of another vector. According to my knowledge, the function std::move() is the "function of choice" for this task. Why is std::move() from Microsoft Visual C++ Express crashing while a hand-crafted loop works as expected?

I am using Microsoft Visual C++ 2015 Update 3. Unfortunately I'm not able to test 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

According to my knowledge the following two pieces of code should work the same way. They should move the elements of added_channels to the end of channels .

This is the first variant 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));
}

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

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

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

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

For insertion into a vector , range insert is preferable to element-by-element push_back (or the equivalent back_inserter ) because it avoids unnecessary reallocations and correctly grows the storage exponentially. The latter is easy to mess up: indiscriminate uses of reserve can easily cause quadratic behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM