Posted By

huanglx on 12/16/11


Tagged

smart memory pointer leak c++


Versions (?)

Memory Leak in Constructor (C++)


 / Published in: C++
 

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

  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  

You need to login to post a comment.