c++ - How to tell the object of the death of another object? -


on work have met 1 bug can described follows. there 2 classes, class , class b:

class { public:     void print(){} };    class b {     a* a; public:     void init(a* _a) {         = _a;     }     void printwitha()     {         a->print();     } };  a* a; b* b; b->init(a);  // code ..... delete a;        // line 1 = null; // code .....  b->printwitha(); // line 2 

object "b" doesn't know nothing state of object "a". in line 1 "a"object has been deleted on line 2 continue use it. when there lot of code easy make such mistake. question following - approch use avoid mistakes? guess use observer pattern - think unjustifiably expensive solution. thank's.

you should use weak ptr (http://en.cppreference.com/w/cpp/memory/weak_ptr)

basically can provide class b weak ptr of a.

whenever comes time access a, can try lock weak ptr see if it's still valid.

#include <memory>  class { public:     void print(){} };    class b {     std::weak_ptr<a> a; public:     void init(std::weak_ptr<a> _a) {         = _a;     }     void printwitha()     {         if (auto spt = a.lock()) {              spt->print();         }     } };  int main() {     std::shared_ptr<a> = std::make_shared<a>();     std::unique_ptr<b> b = std::make_unique<b>();     b->init(a);      // code .....     = nullptr;     // code .....      b->printwitha(); // line 2     return 0; } 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -