簡體   English   中英

在C ++ 11中為線程禁用了副本分配

[英]Copy assignment is disabled for thread in C++11

void exec_produce(int duration) {
    //阻止線程運行到duration秒
    this_thread::sleep_for(chrono::seconds(duration));
    //this_thread::get_id()獲取當前線程id
    cout << "exec_produce thread " << this_thread::get_id()
    << " has sleeped " << duration << " seconds" << endl;
}

int main(int argc, const char *argv[])
{
    thread threads[5];
    cout << "create 5 threads ..." << endl;
    for (int i = 0; i < 5; i++) {
        threads[i] = thread(exec_produce, i + 1);
    }
    cout << "finished creating 5 threads, and waiting for joining" << endl;
    //下面代碼會報錯,原因就是copy操作不可用,相當於是delete操作,所以報錯
    /*for(auto it : threads) {
       it.join();
    }*/
    for (auto& it: threads) {
        it.join();
    }
    cout << "Finished!!!" << endl;
    system("pause");
    return 0;
 }

我想知道為什么代碼threads[i] = thread(exec_produce, i + 1); 是正確的? 是否不使用復印功能? 我看到規則如下:

1)移動分配操作:thread&operator =(thread && rhs)noexcept,如果當前對象不可連接,則需要向移動分配操作傳遞一個正確的值引用(rhs); 如果當前對象可以連接,則終止()錯誤。

2)禁用復制分配:thread&operator =(const thread&)= delete,無法復制線程對象。

不,這是移動功能。

使用= ,如果可能(即,傳遞一個右值並且存在一個移動賦值運算符),將執行移動。 只有在不可能的情況下,才會嘗試進行復制。 應該以最便宜的操作為默認設置。

您可以在引用的規則中清楚地看到,兩個操作都可以由=運算符表示。

不,代碼正確。

threads[i] = thread(exec_produce, i + 1); 將調用移動分配。 thread(exec_produce, i + 1)是一個r值,因為它在內存中沒有定義的位置(它剛剛創建並且尚未存儲在變量中)。 因此,將調用移動分配。

暫無
暫無

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

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