/ Published in: C++
An example showing how to solve the memory leak problem in constructor
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
class Number { public: Number() { cout << "number constructor" << endl; } ~Number() { cout << "number destructor" << endl; } }; class Photo { public: Photo() { cout << "photo constructor" << endl; } ~Photo() { cout << "photo destructor" << endl; } }; class Voice { public: Exp() { throw -1; } ~Exp() {} }; class Entry { public: Entry() : m_number(new Number()), m_photo(new Photo()), m_voice(new Voice()) {} ~Entry() {} private: const auto_ptr<Number> m_number; const auto_ptr<Photo> m_photo; const auto_ptr<Voice> m_voice; }; try { Entry * entry = new Entry(); } catch ( int e ) { cout << "m_number and m_photo have been cleaned up" << endl; }