lundi 14 juin 2021

Why is copying or assigning objects of this class considered dangerous?

From "C++ Concurrency in Action" by Anthony Williams.

The author defines a thread_guard class which, is passed a reference to a std::thread upon construction, and upon destruction, attempts to join() that same thread.

Here is the definition

class thread_guard
{
    std::thread& t;
    public:
        explicit thread_guard(std::thread& t_):t(_t){}
    ~thread_guard()
    {
        if(t.joinable())
        {
           t.join();
        }
    }
    thread_guard(thread_guard const&)=delete;  // why?
    thread_guard operator=(thread_guard const&)=delete;  // why?
}

My question is why are the copy constructor and assignment operator disallowed (with delete)? The author says that copying would be dangerous because the copied thread_guard object "might then outlive the scope of the thread it was joining". But I'm confused - isn't that a risk anyway, even with the original object (that the object will outlive the scope of the thread)? Isn't that why there is a check in the destructor, if t.joinable()?

What fundamental thing have I missed here.

(Related: thread_guard vs scoped_thread)

Aucun commentaire:

Enregistrer un commentaire