Memory Leak in Constructor (C++)


/ Published in: C++
Save to your folder(s)

An example showing how to solve the memory leak problem in constructor


Copy this code and paste it in your HTML
  1. class Number {
  2. public:
  3. Number() { cout << "number constructor" << endl; }
  4. ~Number() { cout << "number destructor" << endl; }
  5. };
  6.  
  7. class Photo {
  8. public:
  9. Photo() { cout << "photo constructor" << endl; }
  10. ~Photo() { cout << "photo destructor" << endl; }
  11. };
  12.  
  13. class Voice {
  14. public:
  15. Exp() { throw -1; }
  16. ~Exp() {}
  17. };
  18.  
  19. class Entry {
  20. public:
  21. Entry() : m_number(new Number()),
  22. m_photo(new Photo()),
  23. m_voice(new Voice())
  24. {}
  25. ~Entry() {}
  26. private:
  27. const auto_ptr<Number> m_number;
  28. const auto_ptr<Photo> m_photo;
  29. const auto_ptr<Voice> m_voice;
  30. };
  31.  
  32.  
  33. try {
  34. Entry * entry = new Entry();
  35. } catch ( int e ) {
  36. cout << "m_number and m_photo have been cleaned up" << endl;
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.