Search code examples
c++multithreadingc++11stdthread

What is the correct way of freeing std::thread* heap allocated memory?


I'm declaring a pointer to a thread in my class.

class A{
   std::thread*    m_pThread;   
   bool StartThread();
   UINT DisableThread();
}

Here is how I call a function using a thread.

bool A::StartThread()
{
    bool mThreadSuccess = false;
    {
       try {
          m_pThread= new std::thread(&A::DisableThread, this);
          mThreadSuccess = true;
      }
      catch (...) {
         m_pDisable = false;
      }

      if(m_pThread)
      {
         m_pThread= nullptr;
      } 
   }
return mThreadSuccess;
}

Here is the function called by my thread spawned.

UINT A::DisableThread()
{
    //print something here.
    return 0;
}

If I call this StartThread() function 10 times. Will it have a memory leak?

for (i = 0; i<10; i++){
    bool sResult = StartThread();
      if (sResult) {
        m_pAcceptStarted = true;
      }
}

Solution

  • What is the correct way of freeing

    m_pThread= new std::thread(&A::DisableThread, this);
    

    The correct way to free a non-array object created using allocating new is to use delete.

    Avoid bare owning pointers and avoid unnecessary dynamic allocation. The example doesn't demonstrate any need for dynamic storage, and ideally you should use a std::thread member instead of a pointer.

    If I call this StartThread() function 10 times. Will it have a memory leak?

    Even a single call will result in a memory leak. The leak happens when you throw away the pointer value here:

    m_pThread= nullptr;
    

    could you add your better solution

    Here's one:

    auto future = std::async(std::launch::async, &A::DisableThread, this);
    // do something while the other task executes in another thread
    do_something();
    // wait for the thread to finish and get the value returned by A::DisableThread
    return future.get()