简体   繁体   中英

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;
 }

I want to know why the code threads[i] = thread(exec_produce, i + 1); is correct? Is it not use the copy function? I see the rule as follows:

1) move Assignment operation: thread& operator= (thread&& rhs) noexcept, if the current object is not joinable, you need to pass a right value reference (rhs) to the move assignment operation; if the current object can be joinable, then terminate () error.

2) Copy assignment is disabled: thread& operator= (const thread&) = delete, thread object cannot be copied.

No, it's the move function.

When using = , a move is performed if possible (that is, if passing an rvalue, and if a move assignment operator exists). Only if not possible will a copy be attempted instead. It should make sense that the cheapest operation is the default.

You can clearly see in the quoted rules that both operations may be represented by the = operator.

No, the code is correct.

The line threads[i] = thread(exec_produce, i + 1); will call the move assignment. thread(exec_produce, i + 1) is a r-value because it does not have a defined location in memory (it just been created and wasn't stored in a variable yet). Therefore, the move assignment will be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM