class A { public: // Constructor A() { m_pMember = new int; } // Destructor ~A() { delete m_pMember; // UNNECESSARY: You can't access that pointer after the destructor! m_pMember = NULL; } int* m_pMember; }; int _tmain(int argc, _TCHAR* argv[]) { // Instantiate A* pA = new A; // Destroy, destructor gets called! delete pA; // THIS IS WRONG, you can't access m_pMember anymore. You can't even check if for NULL! // This probably won't crash in 99% of the cases, but it can crash! if (pA->m_pMember) { // Do something } return 0; }
看起来他的程序的确能证明他的观点。但是他忘记了一点,关于对象的copying。如果对象pA在delete之前copying给了其他对象,那么结果可是大不一样啊!让我们稍微改动下程序再看看效果:
class A { public: A() { m_pMember = new int;} ~A() { delete m_pMember; } int* m_pMember; }; int _tmain(int argc, _TCHAR* argv[]) { A* pA = new A(); A* pB = pA; delete pA; if (pB->m_pMember) { int temp = *pB->m_pMember; //Crash } return 0; }