xcode 错误:调用“std::__1::unique_ptr<A, std::__1::default_delete<A> >”的隐式删除复制构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39724272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<A, std::__1::default_delete<A> >'
提问by Abhishek
I'm constructing an object that takes a std::vector<std::unique_ptr<A> >
as an argument. The constructor is defined like this
我正在构建一个以 astd::vector<std::unique_ptr<A> >
作为参数的对象。构造函数是这样定义的
class B {
std::vector <std::unique_ptr<A> > e_;
public:
B(std::vector <std::unique_ptr<A> > e) : e_(std::move(e)){}
};
and then used as
然后用作
std::vector <std::unique_ptr<A> > e;
B b(e);
and Xcode presents the error
和 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)...);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
Why is the error still persisting even though i am using std::move()
?
为什么即使我正在使用错误仍然存在std::move()
?
EDIT: 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?
编辑:如果我使用B b(std::move(e))
而不是,错误似乎消失了B b(e))
,有没有办法将move
逻辑移动到函数的实现中?
回答by atb
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:
您的构造函数参数是按值传递的,这将进行复制,但您不能复制 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)){}
};
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:
但是......我同意其他评论,这是糟糕的设计。如果你想B
拥有e
但也想在e
外面操作,B
那么它应该是一个公共成员,不需要花哨的构造函数:
class B {
public:
std::vector <std::unique_ptr<float> > e_;
};
回答by Slava
Why is the error still persisting even though i am using std::move()?
为什么即使我使用 std::move() 错误仍然存在?
Because you are moving argument of ctor of B
into member, which does not mean that variable e
should or could be moved.
因为您正在将 ctor of 的参数移动B
到成员中,这并不意味着该变量e
应该或可以移动。
is there any way to move the move logic to the implementation of the function?
有没有办法将移动逻辑移动到函数的实现中?
Even if it is possible, you should not do it. It should be clear for reader of code where e
is used, that it was moved and cannot be used anymore.
即使有可能,你也不应该这样做。代码的读者应该清楚在哪里e
使用它,它被移动了并且不能再使用了。