In this article we will discuss how to use std::thread object as member variable inside class and its benefits.

As std::thread objects are move only, therefore while designing a class that use std::thread as member variable, we need to take care that objects of this class should also be move only.

Creating Move-only class with std::thread as member variable

Let’s create a ThreadWrapper class that has std::thread as member variable and make it move-able by,

  • Deleting its copy constructor and assignment operator.
  • Defining Move constructor and Move assignment operator.

Its parameterized constructor will accept callback / function pointer / funcion object as argument that will be used as thread function by internal thread object i.e.

Move Constructor & Assignment Operator

In Move constructor and assignment operator we need to move the thread object i.e.

In Move assignment operator we first need to join the current thread  object if its joinable, before replacing it with new thread object.

In the destructor of ThreadWrapper we need to join the thread object. It is necessary because if thread object is destructed without joining, then it will terminate the application i.e.

Now Let’s create a ThreadWrapper object, now when this object will be destructed, internal thread will be joined in destructor i.e

Also, we can create a vector of ThreadWraper i.e.

We don’t even need to join the threads separately , it will be automatically joined when vector is destructed. We can also change the content of vector i.e.

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.