为什么我收到编译错误“使用已删除的函数 'std::unique_ptr ...”

新手上路,请多包涵

我收到一个巨大的编译错误消息

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)); }

当我将自定义比较器传递给 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());

 }

我在 Windows 7 机器上使用 gcc 6.1.0。

我错过了什么?

问候。

PG

原文由 gath 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

您仍然收到错误的原因:

std::set_difference 确实在内部 _复制_:

将排序范围 [first1, last1) 中未在排序范围 [first2, last2) 中找到的元素复制到从 d_first 开始的范围。

http://en.cppreference.com/w/cpp/algorithm/set_difference

如果要编译代码,请改用 std::shared_ptr 。

请记住,标准库针对对象而不是指针进行了优化。如果您使用指针,则必须自己进行所有权管理。

原文由 Trevir 发布,翻译遵循 CC BY-SA 3.0 许可协议

std::unqiue_ptr 的主要特点是不可复制。这是设计使然,这个名字也告诉了你很多。

但是, CompareDiff 尝试按值获取其参数。那需要一个副本。取而代之的是 std::unique_ptr<..> const& - 不需要副本。

原文由 MSalters 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题