C++ 为什么会出现编译错误;已删除函数的使用';标准::唯一的“ptr…”;
我收到一个巨大的编译错误消息C++ 为什么会出现编译错误;已删除函数的使用';标准::唯一的“ptr…”;,c++,C++,我收到一个巨大的编译错误消息 c:\mingw\include\c++\6.1.0\bits\predefined_ops.h:123:18: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Deduction; _Dp = std::default_delete<Deduct
c:\mingw\include\c++\6.1.0\bits\predefined_ops.h:123:18: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Deduction; _Dp = std::default_delete<Deduction>]'
{ return bool(_M_comp(*__it1, *__it2)); }
我在Windows7机器上使用GCC6.1.0
我错过了什么
问候
PG您不能复制构建一个
唯一的\u ptr
,因为它是一个已删除的函数,您可以移动唯一指针以转移所有权,但由于您希望函子比较某些内容,因此需要通过引用传递这些unique\u ptr
,std::unqiue\u ptr
的主要功能是它不能被复制。这是故意的,名字也告诉了你很多
但是,
CompareDiff
尝试按值获取其参数。那需要一份复印件。取而代之的是,使用一个std::unique\u ptr const&
-不需要任何副本。您仍然收到错误的原因:
std::set_差异是否在内部复制:
将排序范围[first1,last1]中未在排序范围[first2,last2]中找到的元素复制到从d_first开始的范围
如果要编译代码,请改用std::shared_ptr
请记住,标准库是针对对象而不是指针进行优化的。如果使用指针,则必须自己进行所有权管理。使用唯一\u ptr
表示函数拥有x
的所有权
使用shared_ptr
表示函数是x
的部分所有者
如果确实要传递唯一\u ptr
并转移所有权,则应将智能指针插入函数参数中
,Herb Sutter也有一些好的想法。您可能需要
auto rPtr1=ded1.get()
但这可能是不相关的。@m过滤器可能根本不需要将ded1
转换为原始指针。只需像常规指针一样使用unique\u ptr
即可:ded1->p\u number
。阅读文档。问题会很明显。@BaummitAugen:如果答案如此明显,你还在等待答案。有什么原因吗“你没有使用std::vector
BTW吗?这可能会容易得多。更改参数,现在传递引用,但我仍然会得到相同的错误。显然不是完全相同的错误,但我可以想象你也在尝试将该指针复制到其他地方。基于我的问题,shared_ptr与unique_ptr有何不同?如何替换我的un?”ique_ptr with shared_ptr?unique_ptr
已禁用复制,shared_ptr
已允许复制(请注意,它是浅拷贝!)编译的程序谢谢!但我希望编译器能告诉我,当我在晚会上晚一点使用unique时,复制操作会发生在什么地方,但也许对未来的读者来说:std::copy
基本上是两个向量上的for循环,比如vec1
和vec2
,它确实是vec2[I]=vec1[I]
。=
就是调用对象的复制构造函数的方法。因为您有唯一的\u ptr
它试图调用它的复制构造函数,该构造函数已被删除,因此出现错误
struct Value{
std::string ded_code;
float amount;
Value(std::string code, float amt):ded_code(code), amount(amt){}
};
struct Deduction{
std::string p_number;
std::vector<std::unique_ptr<Value>> values;
Deduction(string pnum, string code, float amt):p_number(pnum){
auto val = std::make_unique<Value>(code, amt);
values.emplace_back(move(val));
}
};
class compute{
public:
vector<unique_ptr<Deduction>> deductions;
void fillDeductions(){
// fill deductions
...
}
};
class CompareDiff{
public:
bool operator()(unique_ptr<Deduction>& ded1, unique_ptr<Deductions>& ded2){
rPtr1 = ded1.get();
rPtr2 = ded2.get();
return ( rPtr1->p_number < rPtr2->p_number);
}
};
...
int main(){
...
// fill two deduction vectors
Compute compA = Compute()
compA.fillDeductions()
Compute compB = Compute()
compB.fillDeductions()
vector<unique_ptr<Deduction>> diffs
set_difference(compA.begin(), compA.end(),
compB.begin(), compB.end(),
inserter(diffs, diffs.begin()), CompareDiff());
}