2016-09-26 1 views
2

は、メッセージなぜ私は、コンパイルエラーになっています「削除関数「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)); } 

を持つ巨大なコンパイルエラーを取得しています。

マイコード:

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を使用しています。

私には何が欠けていますか?

よろしくお願いいたします。

あなたは、その削除機能以来unique_ptrを構築コピーすることはできませんPG

+0

おそらく 'auto rPtr1 = ded1.get()'が必要ですが、それはおそらく無関係です。 – MSalters

+0

@MSaltersおそらく、 'ded1'を生ポインタにまったく変換する必要はありません。通常のポインタのように 'unique_ptr'を使います:' ded1-> p_number'。 –

+0

ドキュメントを読んでください。問題は明らかでした。 –

答えて

3

あなたはまだエラーを取得する理由:

のstd ::のset_differenceは内部コピーん:あなたはあなたのコードをコンパイルしたい場合は、STDを

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

使用代わりに:shared_ptr。

標準ライブラリはオブジェクト用に最適化されており、ポインタ用には最適化されていません。ポインタを使用する場合は、所有権管理を自分で行う必要があります。

+0

私の問題に基づいてshared_ptrとunique_ptrはどのように違うのですか?私はどのように私のunique_ptrをshared_ptrに置き換えるのですか? – gath

+0

'unique_ptr'はコピーが禁止されています、' shared_ptr'はコピーが許可されています(ただし、それは浅いコピーです!) – Trevir

+0

おかげさまでコンパイルされたプログラム!しかし私は、コンパイラが私に、コピー動作が正確にどこにあるのかを表示することを望みます。unique_ptr – gath

3

、あなたが所有権を譲渡するために独自のポインタを移動させることができますが、ファンクタは、あなたが参照によってそれらのunique_ptrを渡す必要が何かを比較したいので、

+0

まだ同じエラーが発生する – gath

4

std::unqiue_ptrの主な特徴は、コピーできないことです。それは設計によるものであり、その名前はあなたに多くを伝えます。

ただし、CompareDiffは引数を値でとろうとします。それにはコピーが必要です。代わりに、std::unique_ptr<..> const&を取ってください。コピーは必要ありません。

+0

引数を変更して参照を渡しますが、同じエラーが表示されます。 – gath

+0

まあ、まったく同じエラーではありませんが、別の場所でそのポインタをコピーしようとしていると思います。 – MSalters

関連する問題