visual c++ 为什么 std::move 崩溃

visual c++ why does std::move crash

我想将一个向量附加到另一个向量的末尾。据我所知,函数 std::move() 是此任务的 "function of choice"。为什么来自 Microsoft Visual C++ Express 的 std::move() 在手工制作的循环按预期工作时崩溃?

我正在使用 Microsoft Visual C++ 2015 Update 3。很遗憾,我无法使用其他编译器对其进行测试。

// 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

据我所知,以下两段代码的工作方式应该相同。他们应该将 added_channels 的元素移动到 channels 的末尾。

这是第一个崩溃的变体:

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

这是第二个有效的版本:

for(auto & ref : added_channels)
{
    channels.push_back(std::move(ref));
}

std::move 移动到特定位置。
如果你想把它插入到vector的后面,你应该使用std::back_inserter

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

这实际上是 move_iterator 实际有用的少数情况之一:

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

对于插入 vector,范围 insert 优于逐个元素 push_back(或等效的 back_inserter),因为它避免了不必要的重新分配和正确地以指数方式增长存储。后者很容易搞砸:不加选择地使用 reserve 很容易导致二次行为。