通过成员函数将唯一 ptr 的向量附加到另一个向量

Append vector of unique ptr to another via member function

我想将唯一 ptrs 向量移动到我存储在 class 中的唯一 ptrs 向量。我在这里将其简化为最小示例:

#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class A
{
public:
    A() = default;  
};


class B
{

public:

    void AddAs(const vector<unique_ptr<A>>& vv)
    {

        vec.insert(vec.end(),
            std::make_move_iterator(vv.begin()),
            std::make_move_iterator(vv.end())
        );
    }

    vector<unique_ptr<A>> vec;
};


int main() {    
    vector<unique_ptr<A>> v;
    for(int i=0; i<10; ++i)
    {
        v.push_back(make_unique<A>());
    }
    B b;
    b.AddAs(v);

    return 0;
}

https://ideone.com/76iNIM

这试图遵循 Inserting a vector of unique_ptr into another vector

的答案

但这并没有像它所说的那样编译,因为它使用了复制运算符。

我敢肯定这是一个愚蠢的问题,但我是 C++ 的新手,我很难看到副本在哪里。

谢谢

您不能从通过 const 引用传递的向量移动,因为移动需要修改。所以将该方法更改为:

void AddAs(vector<unique_ptr<A>>&& vv)

按值传递也可以:

void AddAs(vector<unique_ptr<A>> vv)

请注意您需要更改调用代码:

b.AddAs(std::move(v));

这实际上很好,因为显示了向量将从中移动的 reader。

live example