简体   繁体   中英

Is it ok to replace std::thread objects?

From what I could gather in C++ online documentation, assigning to a joined std::thread object should call its destructor and represents a legitimate operation. Is this the case?

Here some example to show what I mean:

#include <thread>
#include <vector>

using namespace std;

int main()
{
    vector<thread> tvec;
    for(int = 0; i < 3; ++i)
    {
        tvec.push_back(thread(foo));
    }
    for(size_t i = 0; i < 3; ++i)
    {
        tvec[i].join();
        tvec[i] = thread(foo); // is this ok?
    }
    for(auto& t : tvec)
    {
        t.join();
    }
}

assigning to a joined std::thread object should call its destructor

No it shouldn't! Destructors are only called when objects are destroyed, hence the name.

and represents a legitimate operation

It's fine as long as the thread is not joinable (as is the case in your example). Otherwise, terminate will be called.

If you were to read the standard, rather than dubious online "documentation", you'd find in [thread.thread.assign]

Effects: If joinable() , calls terminate() . Otherwise, assigns the state of x to *this and sets x to a default constructed state.

Calling the assignment operator on a thread checks to see if the thread is joinable() if it is then std::terminate() is called. If it is not then it assigns the state of the thread on the right hand side to the thread being assigned to. It then leaves the thread on the right hand side in a default constructed state.

This is called a move assignment. The actual assignment operator is deleted.

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