template for safe "delete this"
Hi ALL,
I'd like to know if it is possible to have a template to implement a
policy to ensure the correct usage for self deleted classes.
For some classes will delete itself in its methods via "delete this" ,
such as a class for modeless dialog, thread, callback, etc.
Here is a non-template version,
#include <iostream>
//to prevent user from calling delete explictly, prevent user from
//using it on the stack
class OnegaDeleteThis
{
public:
OnegaDeleteThis()
{
}
void DeleteMe()
{// this may be entry routine of a thread, callback etc.
delete this;
}
protected:
~OnegaDeleteThis()
{
//prevent user from calling delete explicitly
}
};
int main()
{
//The expected usage
OnegaDeleteThis *a = new OnegaDeleteThis;
a->DeleteMe();
//Stop the following unexpected usage
//Compiling error for explicit delete
//delete a;
//Compiling error for object on stack
//TestDeleteThis obj_on_stack;
return 0;
}
Back to my question. I expect a template to implement the policy, so
that it can be reused for different classes that have the same
requirement. I have a glance at Loki but don't find the answer. Looking
forward to see others' opinion.
Thanks a lot.