Search code examples
c++variable-assignmentstdthread

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

Solution

  • 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.