D
D
Daniel2018-10-19 23:25:42
C++ / C#
Daniel, 2018-10-19 23:25:42

How to avoid a memory leak in a class with a field pointer to its stream?

In the class, a method is launched in a separate thread, which should take care of releasing resources, but I cannot free the pointer to the thread itself.
The class looks like this

class Listener{
  private :
   std::thread th;  // указатель на поток, не могу  его удалить с кучи
  char *str;         // удалятся
public:
Listener(char *_str,int len){
       str=new char[len];
          strncpy(str,_str,len);
        th=new std::thread(run,this); // запускаю выполнение
}
    static void run(Listener *_this){
         /* body
        */
          delete  [] _this->str;    //  удаляю строку
          // delete _this->th;  // ОШИБКА критическая, если  добавить
         delete _this;                   // вызываю деконструктор и удаляю this : Listner
}
};
void main(){ 
  for(;;){
     Listener *l=new Listener("12345678912345");

}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
reishi, 2018-10-27
@reishi

Before destroying the std::thread object, you must call join or detach on the thread object, otherwise std::terminate is thrown ( what you call a fatal error )
I advise you to read the book Parallel C++ Programming in Action. P... .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question