我的消息收到了很大的编译错误
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)); }
Run Code Online (Sandbox Code Playgroud)
当我将自定义比较器传递给STL set_difference函数时.
我的代码:
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());
}
Run Code Online (Sandbox Code Playgroud)
我在Windows 7机器上使用gcc 6.1.0.
我错过了什么?
问候.
PG
其主要特点std::unqiue_ptr是无法复制.这是设计,名称告诉你.
但是,CompareDiff试图通过值来获取其参数.这需要一份副本.相反,采取std::unique_ptr<..> const&- 不需要副本.
你仍然得到一个错误的原因:
std :: set_difference在内部复制:
将排序范围[first1,last1]中的元素(在排序范围[first2,last2]中找不到)复制到从d_first开始的范围.
http://en.cppreference.com/w/cpp/algorithm/set_difference
如果您希望编译代码,请改用std :: shared_ptr.
请记住,标准库是针对对象优化的,而不是针对指针的.如果使用指针,则必须自己进行所有权管理.
您不能复制构造 aunique_ptr因为它是一个已删除的函数,您可以移动唯一指针来转移所有权,但由于您希望函子来比较某些内容,因此您需要unique_ptr通过引用传递这些内容。