code_junkie

C++ using scoped_ptr as a member variable

Nov 14th, 2011
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. class Example {
  2. public:
  3. // ...
  4.  
  5. private:
  6. boost::scoped_ptr<Owned> data;
  7. };
  8.  
  9. class C
  10. {
  11. Owned * o1;
  12. Owned * o2;
  13.  
  14. public:
  15. C() : o1(new Owned), o2(new Owned) {}
  16. ~C() { delete o1; delete o2;}
  17. };
  18.  
  19. auto_ptr<int> a(new int), b;
  20. // oops, after this, a is reset. But a copy was desired!
  21. // it does the copy&reset-of-original, but it's not restricted to only temporary
  22. // auto_ptrs (so, not to ones that are returned from functions, for example).
  23. b = a;
  24.  
  25. ~Example() { ptr.~scoped_ptr<Owned>(); }
  26.  
  27. class MyClass
  28. {
  29. public:
  30. MyClass();
  31. MyClass(MyClass const& copy);
  32. MyClass& operator=(MyClass const& copy);
  33. ~MyClass();
  34.  
  35. private
  36. Data* d1;
  37. Data* d2;
  38. };
  39.  
  40. MyClass::MyClass()
  41. :d1(NULL),d2(NULL)
  42. {
  43. // This is the most trivial case I can think off
  44. // But even it looks ugly. Remember the destructor is NOT called
  45. // unless the constructor completes (without exceptions) but if an
  46. // exception is thrown then all fully constructed object will be
  47. // destroyed via there destructor. But pointers don't have destructors.
  48. try
  49. {
  50. d1 = new Data;
  51. d2 = new Data;
  52. }
  53. catch(...)
  54. {
  55. delete d1;
  56. delete d2;
  57. throw;
  58. }
  59. }
Add Comment
Please, Sign In to add comment