使用 std::move 在开头插入向量的中间元素不起作用

Using std::move to insert middle element of a vector at the beginning not working

我有一个包含几个元素的向量。我尝试插入一个它自己的元素,在开始时使用插入和移动 -

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;
}

Ideone link - https://ideone.com/7T9ubT

现在,我知道以不同的方式编写它可以确保插入正确的值。但我特别想知道的是为什么这行不通 -

v.insert(v.begin(), std::move(v[4]));

以及(在我上面的代码中)值 30 是如何插入到矢量开头的?提前致谢! :)

v[4] 是对向量元素的引用。 insert 使对超过插入点的元素的所有引用和迭代器无效(在您的示例中都是如此)。所以你会得到未定义的行为——引用在 insert 函数内的某处不再有效。