[英]Why am I getting compile error “use of deleted function '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
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。
請記住,標准庫是針對對象優化的,而不是針對指針的。 如果使用指針,則必須自己進行所有權管理。
你不能復制構造unique_ptr
因為它是一個已刪除的函數 ,你可以移動唯一的指針來轉移所有權,但是你需要一個函子來比較你需要通過引用傳遞那些unique_ptr
的東西。
使用unique_ptr<x>
表示函數承擔x
所有權。
使用shared_ptr<x>
表示函數是x
部分所有者。
如果您確實要傳遞unique_ptr
並轉移所有權,則應move
智能指針move
到函數參數中。
關於傳遞智能指針的更多注釋 ,Herb Sutter在這個CppCon講話中有一些好的想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.