[英]Error: Use of deleted function std::unique_ptr
I am trying to pass a unique_ptr into a custom vector class but I am receiving the error in the subject title.我正在尝试将 unique_ptr 传递给自定义向量 class 但我收到主题标题中的错误。
I understand that you cannot copy a unique_ptr and so I am trying to use std::move() when passing it, however that doesn't seem to solve my problem... Where am I going wrong?我知道您无法复制 unique_ptr ,因此我在传递它时尝试使用 std::move() ,但这似乎并不能解决我的问题......我哪里出错了?
Thanks in advance提前致谢
template<typename T>
class VectorSelectable {
public:
void Add(const T& v) {
m_Items.push_back(move(v));
}
private:
vector<T> m_Items;
};
class FunctionType {
int m_Data;
};
int main()
{
VectorSelectable<unique_ptr<FunctionType>> vec;
vec.Add(move(make_unique<FunctionType>()));
return 0;
}
Edit: Added 'const' to 'Add(const T& v)'编辑:将 'const' 添加到 'Add(const T& v)'
If you want to allow both copy-via-const-ref and move-via-rvalue-ref, you can either template your Add
method and use the universal forwarding reference technique, or write two overloads explicitly:如果你想同时允许 copy-via-const-ref 和 move-via-rvalue-ref,你可以模板化你的Add
方法并使用通用转发引用技术,或者显式编写两个重载:
void Add(const T& v) {
m_Items.push_back(v);
}
void Add(T&& v) {
m_Items.push_back(std::move(v));
}
or或者
template <typename U>
void Add(U&& v) {
m_Items.push_back(std::forward<U>(v));
}
The Add()
accepts an lvalue reference of T
, but move(make_unique<FunctionType>())
returns an rvalue reference, you cannot bind an rvalue to an lvalue reference. Add()
接受T
的左值引用,但move(make_unique<FunctionType>())
返回右值引用,您不能将右值绑定到左值引用。
You can turn Add()
into a template function and use forwarding references to accept lvalues and rvalues and move them into your m_Items
.您可以将Add()
转换为模板 function 并使用转发引用来接受左值和右值并将它们移动到您的m_Items
中。
template<class U>
void Add(U&& v) {
m_Items.push_back(move(v));
}
@Max Peglar-Willis The problem here is that somewhere, your code is attempting to call the "copy-assignment" operator. @Max Peglar-Willis这里的问题是,在某个地方,您的代码正试图调用“复制分配”运算符。
This causes the compiler to attempt to generate a copy-assignment operator which calls the copy-assignment operators of all the subobjects.这会导致编译器尝试生成一个复制赋值操作符,该操作符调用所有子对象的复制赋值操作符。 Eventually, this leads to an attempt to copy a unique_ptr,最终,这导致尝试复制 unique_ptr,
an operation that is not possible.不可能的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.