C++ 使用std::move在开始时插入向量的中间元素无效

C++ 使用std::move在开始时插入向量的中间元素无效,c++,c++11,pointers,vector,move,C++,C++11,Pointers,Vector,Move,我有一个有几个元素的向量。我尝试插入它自己的一个元素,开始时使用insert和move- v.insert(v.begin(), std::move(v[4])); 这在开头插入了错误的元素。完整代码- #include <iostream> #include <vector> using namespace std; struct Node { int* val; }; // Util method which prints vector void pr

我有一个有几个元素的向量。我尝试插入它自己的一个元素,开始时使用insert和move-

v.insert(v.begin(), std::move(v[4]));
这在开头插入了错误的元素。完整代码-

#include <iostream>
#include <vector>

using namespace std;

struct Node
{
    int* val;
};

// Util method which prints vector
void printVector(vector<Node>& v)
{
    vector<Node>::iterator it;

    for(it = v.begin(); it != v.end(); ++it)
    {
        cout << *((*it).val) << ", ";
    }

    cout << endl;
}

int main() {
    vector<Node> v;

    // Creating a dummy vector
    v.push_back(Node()); v[0].val = new int(0);
    v.push_back(Node()); v[1].val = new int(10);
    v.push_back(Node()); v[2].val = new int(20);
    v.push_back(Node()); v[3].val = new int(30);
    v.push_back(Node()); v[4].val = new int(40);
    v.push_back(Node()); v[5].val = new int(50);
    v.push_back(Node()); v[6].val = new int(60);

    cout << "Vector before insertion - ";
    printVector(v); // Prints - 0, 10, 20, 30, 40, 50, 60,

    // Insert the element of given index to the beginning
    v.insert(v.begin(), std::move(v[4]));

    cout << "Vector after insertion - ";
    printVector(v); // Prints - 30, 0, 10, 20, 30, 40, 50, 60,
    // Why did 30 get inserted at the beggning and not 40?

    return 0;
}

在我上面的代码中,值30是如何插入到向量开头的?提前谢谢!:

v[4]是对向量元素的引用。insert使对超过插入点的元素的所有引用和迭代器无效—在您的示例中,所有引用和迭代器都是如此。因此,您会得到未定义的行为-该引用在insert函数中的某个位置不再有效。

如果您不在意,msvc 19.00.24215.1会在插入后给出向量-40,0,10,20,30,40,50,60,
v.insert(v.begin(), std::move(v[4]));