Monday, March 24, 2008

Preventing object creation on stack

In C++, sometimes you don't want the user of your class to create the object of it on stack, because the stack resource is rare. Is there any way to do this?
Yes!!!
What you should do is to make your destructor private, rather than public or protected.
You can do like this:
class CTest {
private:
~CTest ();
}
Why only private, because if you make it protected, yes the object this class can't not be created on stack, but it's derived class can!

Then, if you want to create the object on stack, like
CTest test;

The compiler is gona complain, the error message is most probably like 'CTest::~CTest' : cannot access private member declared in class CTest'.

That's because the compiler will actually check if it can delete the object if it's created on stack, because it's compiler's business to take care of this. If you do like:
CTest* test
or
CTest* test = new CTest
It's gona be fine, because the only thing you put on the stack is just the pointer, compiler don't even have to call the destructor of the pointer.
Then, how do you delete the object whose destructor is private?? Just use delete operator is not going to work, because delete operator is not a part of the CTest class. So you have to provide a function which will delete the object itself.
It's like:
void CTest::Release()
{
delete this;
}
Since "delete this" is not a "good manner"(it works, but it's not recommended), you have to pay more attention when you use this. You have to make sure that the object is not created by "new[]". You have to make sure Release is the last function you call on this object, etc.