2016-09-27 94 views
2

拷贝构造函数我正在构造一个以std::vector<std::unique_ptr<A> >作为参数的对象。构造函数定义这样错误:调用隐式删除的'std :: __ 1 :: unique_ptr <A,std :: __ 1 :: default_delete <A>>'

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中介绍错误

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()还是坚持?

编辑:错误似乎消失如果我使用B b(std::move(e))而不是B b(e)),有什么办法将move逻辑移动到函数的实现?

+1

默默移动是*不好*。如果您正在从呼叫者的向量中移出,则应在呼叫者的代码中明确说明向量正在从中移出。 –

回答

0

你的构造函数参数是传值的值,它会复制,但你不能复制std :: unique_ptr。通过参考应该工作:

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那么它应该是一个公共成员,不需要花哨的构造:

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

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

因为你是移动的B构造函数的参数转换为成员,这并不意味着变量e应该或可以移动。

is there any way to move the move logic to the implementation of the function?

即使有可能,你也不应该这样做。代码的读者应该清楚哪里使用e,它已被移动并且不能再使用。

相关问题