會自殺的類別

坦白說,我從沒想過物件可以自殺這件事情。當我看到這樣寫的時候,實在是很令我驚訝…實驗的結果,還真的是可以。

#include 
class SuicideSample {
public:
SuicideSample() { std::cout << "ctor." << std::endl; }
~SuicideSample() { std::cout << "dtor." << std::endl; }
void DoIt( void ) {
delete this;
}
};
int main( int argc, char* argv[] )
{
SuicideSample* obj=new SuicideSample();
obj->DoIt();
// of course, object can kill itself, but if you try to kill it again
// program will crash.
//delete obj;
return 0;
}