I've been snooping around trying to figure whether or not this was completely safe. I've noticed that if you were to simply "delete this" you might have occurrences where the deleted pointer is still in use elsewhere in the program. To prevent this, you'd need to dereference it and perform a check to ensure that the pointer is valid.
Now, the question: is using const_cast on the this pointer safe?
I've whipped up a quick example below:
#include "stdafx.h"
class myclass
{
private:
int *integer;
public:
myclass(int a, int b)
{
integer = new int[1];
*integer = a - b;
if(!lessthannaught(*integer))
{
delete this;
const_cast<myclass *>(this) = 0;
}
}
~myclass()
{
delete integer;
printf("Deconstructor\n");
}
bool lessthannaught(int i)
{
return i < 0;
}
};
int main()
{
myclass *_class;
_class = new myclass(3, 1);
if(!_class)
printf("Memory freed from within constructor\n");
else
{
printf("Freeing\n");
delete _class;
}
printf("----------\n");
_class = new myclass(2, 3);
if(!_class)
printf("Memory freed from within constructor\n");
else
{
printf("Freeing\n");
delete _class;
}
while(1);
return 0;
}
I've tested it and it appears to work, but is such a method recommended (or better yet, are there alternate methods around it)? Thanks!