簡體   English   中英

擴展std :: thread的ref對象傳遞的范圍

[英]extend scope of pass by ref object for std::thread

為了演示這個問題,讓我給出一個簡短的代碼-

void someMethod() {

  // CustomType obj;
  const auto obj = getCustomTypeObj();

  std::thread([](customType &obj) {
    // some delay
    obj.doSomething();
    obj.close();
    // can now be destructed
  }).detach();

  // similarly for std::async
  std::async(std::launch::async, [](customType &obj){
    obj.doSomething();
    obj.close();
  }

  // there might not be any use of obj here

  // should not be destructed here because std::thread might not get it.

}

在上面的代碼中,構造了一個CustomType類型對象,為其刪除了副本構造函數。 因此,我必須在任何地方通過引用傳遞它,或者在相關范圍內從頭開始創建它。 但是,對於我目前正在處理的1種情況,不可能在std::thread的執行方法內的相關范圍內創建它。

我擔心的是obj可能在std::thread甚至完成其工作之前就被破壞了,然后我不知道會發生什么。 因此,我該如何解決將其范圍擴展到std :: thread的lambda的問題。

順便說一句,您的代碼不正確,您沒有傳遞對象,因此您的代碼應改為:

  auto obj = getCustomTypeObj();

  std::thread([](customType &obj) {
    // some delay
    obj.doSomething();
    obj.close();
    // can now be destructed
  }, std::ref( obj ) ).detach();

為避免對象生存期出現問題,請按值將對象傳遞給lambda或函數,然后將對象移動到該位置:

  auto obj = getCustomTypeObj();

  std::thread([](customType arg) { // note by value, not reference
    // some delay
    arg.doSomething();
    arg.close();
    // arg will be destroyed here
  }, std::move( obj ) ).detach(); // object moved

現在,lambda或函數擁有該對象,並且該對象將在函數末尾銷毀。 這是一個實時示例 ,我只是在那里使用std::unique_ptr而不是customType作為已禁用復制以驗證移動有效的類型。

暫無
暫無

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

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