Is there a safe way to have a std::thread as a member of a class?

You can use a thread in combination with move semantics:

class MyClass final
{
private:
    std::thread mythread;
    void _ThreadMain();
public:
    MyClass()
        : mythread{} // default constructor
    {
        // move assignment
        mythread = std::thread{&MyClass::_ThreadMain, this};
    }
};

The move assignment operator is documented on the following page. In particular, it is noexcept and no new thread is created.

  • http://en.cppreference.com/w/cpp/thread/thread/operator%3D

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)