c++ - 为什么我会收到编译错误 "use of deleted function ' std::unique_ptr ...”

标签 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<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

最佳答案

您仍然收到错误的原因:

std::set_difference 在内部复制:

Copies the elements from the sorted range [first1, last1) which are not found in the sorted range [first2, last2) to the range beginning at d_first.

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

如果您希望您的代码能够编译,请改用 std::shared_ptr。

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

关于c++ - 为什么我会收到编译错误 "use of deleted function ' std::unique_ptr ...”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39703954/

相关文章:

php - 将 php5 模块移植到 php 7 和编译时出现 zend_string 问题

c++ - 引用传递行为及其范围

c++ - 使用 C 和 C++ 文件编译库时发出警告

c++ - 作为容器的初始化程序列表不起作用

c++ - 适用于 C++ 的 Windows Azure SDK

C++ 检查引用类型

c++ - 我如何从终端的谷歌测试套件中获取 C++ 代码超量?

c++ - 创建注册表项以将文件扩展名与 C++ 中的应用程序相关联

c++ - 如何在 C++ 中使用 Windows API 隐藏桌面图标?

c++ - 为什么继承的结构成员在 union 中不可访问?