#include <iostream> using namespace std; template<typename Type> class AutoRelease { typedef void (Type::* pFunc)(void); public: AutoRelease(Type* p, pFunc pfunc) :m_class(p), m_pFunc(pfunc) {} ~AutoRelease() { cout<< "release memory"<<endl; (m_class->*m_pFunc)(); } private: Type* m_class; pFunc m_pFunc; }; class TestClass { public: TestClass(){cout<<"TestClass()"<<endl;} void release() { cout<<"release()"<<endl; delete ptr; ptr = NULL; } void excute(void) { AutoRelease<TestClass> autoR(this, &TestClass::release); cout<<"excute()"<<endl; this->testMem(); } void testMem(void) { if(NULL == ptr) { cout<< "ptr is NULL" <<endl; } else { cout << "ptr is not NULL" <<endl; } } void testInt() { cout<<this->tempVal<<endl; } static TestClass* getInstance(); int tempVal; private: static TestClass* ptr; }; TestClass* TestClass::ptr = NULL; TestClass* TestClass::getInstance() { if(NULL == ptr) { ptr = new TestClass; } return ptr; } int main(void) { TestClass* p = TestClass::getInstance(); p->excute(); p->testMem(); cout << (NULL==p)<< endl; p->excute(); p->testMem(); delete p; TestClass* p1 =new TestClass; p1->tempVal = 100; delete p1; delete p1; /* 把p1=NULL 的注释打开和关闭,运行对比下。 可以参考 深入探究C++对象模型 中“成员函数调用” 解释 */ //p1 = NULL; p1->testMem(); p1->testInt(); //思考:为什么delete之后还可以执行? NULL 还可以调用成员函数? p1->testInt(); p1->testInt(); return 0; }