In general, if you have a class that inherits from a Thread
class, and you want instances of that class to automatically deallocate after they are finished running, is it okay to delete this
?
Specific Example:
In my application I have a Timer
class with one static
method called schedule
. Users call it like so:
Timer::schedule((void*)obj, &callbackFunction, 15); // call callbackFunction(obj) in 15 seconds
The schedule
method creates a Task
object (which is similar in purpose to a Java TimerTask object). The Task
class is private
to the Timer
class and inherits from the Thread
class (which is implemented with pthreads). So the schedule
method does this:
Task *task = new Task(obj, callback, seconds);
task->start(); // fork a thread, and call the task's run method
The Task
constructor saves the arguments for use in the new thread. In the new thread, the task's run
method is called, which looks like this:
void Timer::Task::run() {
Thread::sleep(this->seconds);
this->callback(this->obj);
delete this;
}
Note that I can't make the task
object a stack allocated object because the new thread needs it. Also, I've made the Task
class private
to the Timer
class to prevent others from using it.
I am particularly worried because deleting the Task
object means deleting the underlying Thread
object. The only state in the Thread
object is a pthread_t
variable. Is there any way this could come back to bite me? Keep in mind that I do not use the pthread_t
variable after the run
method finishes.
I could bypass calling delete this
by introducing some sort of state (either through an argument to the Thread::start
method or something in the Thread
constuctor) signifying that the method that is forked to should delete
the object that it is calling the run
method on. However, the code seems to work as is.
Any thoughts?