错误:调用'std :: __ 1 :: unique_ptr< A,std :: __ 1 :: default_delete< A>隐式删除的副本构造函数>'

问题描述:

我正在构造一个对象,该对象采用 std :: vector< std :: unique_ptr< A> > 作为参数。构造函数的定义如下:

I'm constructing an object that takes a std::vector<std::unique_ptr<A> > as an argument. The constructor is defined like this

class B {
    std::vector <std::unique_ptr<A> > e_;

public:
    B(std::vector <std::unique_ptr<A> > e) : e_(std::move(e)){}

};

然后用作

std::vector <std::unique_ptr<A> > e;
B b(e);

并且Xcode出现错误

and Xcode presents the error

error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<A, std::__1::default_delete<A> >'
:new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
                 ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`

即使我使用 std :: move(),为什么错误仍然持续存在?

Why is the error still persisting even though i am using std::move()?

编辑:如果我使用 B b(std :: move(e))而不是 B b(e)),有什么方法可以将 move 逻辑移动到该函数的实现中?

the error seems to vanish if i use B b(std::move(e)) instead of B b(e)), is there any way to move the move logic to the implementation of the function?

您的构造函数参数将通过值传递,这将进行复制,但是您无法复制std :: unique_ptr。通过引用传递应该起作用:

Your constructor argument is pass by value which will make a copy, but you cannot copy a std::unique_ptr. Passing by reference should work:

class B {
    std::vector <std::unique_ptr<float> > e_;

public:
    B(std::vector <std::unique_ptr<float> >& e) : e_(std::move(e)){}

};

但是...我同意其他评论,认为这是不好的设计。如果您想让 B 拥有 e 但还想操纵 e B 之外,那么它应该是公共成员,不需要花哨的构造函数:

But...I agree with the other comments that this is bad design. If you want B to own e but also want to manipulate e outside of B then it should be a public member, no fancy constructor needed:

class B {
public:
    std::vector <std::unique_ptr<float> > e_;
};