Advertisement
Guest User

Untitled

a guest
Jun 27th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. // C++03
  2. class Foo {
  3.     std::vector<MyThing*> thingContainer_;
  4. public:
  5.     ~Foo() { // have to manually delete everything
  6.         std::vector<MyThing*>::iterator it = thingContainer_.begin();
  7.         while(it != thingContainer.end()) {
  8.             delete *it;
  9.             it = thingContainer_.erase(it);
  10.         }
  11.     }
  12.  
  13.     MyThing* add_thing() {
  14.         thingContainer_.push_back(new MyThing);
  15.         return thingContainer_.back();
  16.     }
  17.  
  18.     void remove_thing(MyThing* thing) {
  19.         std::vector<MyThing*>::iterator it = thingContainer_.begin();
  20.         for(; it != thingContainer_.end(); ++it) {
  21.             if(*it == thing) {
  22.                 delete *it;  // manually delete...
  23.                 thingContainer_.erase(it);
  24.                 return;
  25.             }
  26.         }
  27.     }
  28. };
  29.  
  30.  
  31. // C++11
  32. class Foo {
  33.     std::vector<std::shared_ptr<MyThing> > thingContainer_;
  34. public:
  35.     ~Foo() {} // Don't need destructor any more! std::shared_ptr deletes all things automatically
  36.  
  37.     std::shared_ptr<MyThing> add_thing() {
  38.         thingContainer_.push_back(new MyThing);
  39.         return thingContainer_.back();
  40.     }
  41.  
  42.     void remove_thing(MyThing* thing) {
  43.         for(auto it = thingContainer_.begin(); it != thingContainer_.end(); ++it) {
  44.             if(*it == thing) {
  45.                 thingContainer_.erase(it);  // automatically also deletes the thing
  46.                 return;
  47.             }
  48.         }
  49.     }
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement