如何将唯一指针从一个向量移动到另一个唯一指针向量?

How do I move a unique pointer from one vector to another vector of unique pointers?

如何在 C++11 中将 unique_ptr 从一个向量移动到另一个 unique_ptr 的向量?第一个向量中的唯一指针应完全删除并添加到第二个向量中。

那么,在那种情况下,您有两个概念上独立的操作:

  1. 正在将元素插入到容器中。当你想抹掉源代码时(这实际上是必要的,因为 std::unique_ptr 是一个移动类型),使用 std::move 启用移动语义。

    destination.emplace(destination.begin() + m, std::move(source[n])); // or .insert()
    
  2. 正在从容器中取出掠夺的元素。

    source.erase(source.begin() + n);
    

<algorithm> 包含 std::move.

的实现
std::vector<std::unique_ptr<int>> v1;
v1.emplace_back(std::make_unique<int>(1));
std::vector<std::unique_ptr<int>> v2;
v2.emplace_back(std::make_unique<int>(2));

std::move(v1.begin(), v1.end(), std::back_inserter(v2));

for (auto &&e : v2)
    std::cout << *e;
 // Prints 21

执行此操作后,v1 将包含 1 个具有 nullptr 值的元素。