簡體   English   中英

為什么我不能在C ++ 14中移動lambda中的std :: unique_ptr?

[英]Why can't I move the std::unique_ptr inside lambda in C++14?

我想在lambda中傳遞一個原始指針,但我不希望它被泄露,如果沒有調用lambda。 它看起來像這樣:

void Clean(std::unique_ptr<int>&& list);

void f(int* list) {
  thread_pool.Push([list = std::unique_ptr<int>(list) ] {
    Clean(std::move(list));  // <-- here is an error.
  });
}

我在Clang 3.7.0中收到錯誤:

錯誤:將類型'unique_ptr <[2 * ...]>'的引用綁定到類型'unique_ptr <[2 * ...]>'的值會丟棄限定符

但是我沒有看到任何限定詞,尤其是掉線。

另外,我在郵件列表上找到了類似的報告 ,但沒有回答。


我應該如何修改我的代碼,以便編譯並按語義按預期工作?

你需要使內部lambda mutable

[this](Pointer* list) {
  thread_pool.Push([this, list = std::unique_ptr<int>(list) ]() mutable {
                                                               ^^^^^^^^^
    Clean(std::move(list));
  });
};

默認情況下,lambdas上的operator()const ,因此您無法在該調用中修改其成員。 因此,內部list行為就像是const std::unique_ptr<int> 當你進行move轉換時,它會轉換為const std::unique_ptr<int>&& 這就是為什么你得到關於刪除限定符的編譯錯誤:你試圖將const rvalue引用轉換為非const rvalue引用。 該錯誤可能沒有那么有用,但它歸結為:你不能move const unique_ptr

mutable修復 - operator()不再是const ,因此該問題不再適用。

注意:如果你的Clean()采用unique_ptr<int>而不是unique_ptr<int>&& ,這更有意義(因為它是一個更明確的,確定性的接收器),那么錯誤會更加明顯:

error: call to deleted constructor of `std::unique_ptr<int>`
note: 'unique_ptr' has been explicitly marked deleted here  

    unique_ptr(const unique_ptr&) = delete
    ^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM