Thanks Pavel. Iam thinking so that would be the point. How to check when ptr has become null?
If you store a pointer to another class, and that class is destroyed, your pointer will become a dangling pointer. You can't check for that unfortunately.
So there are a few things that you can do:
- store std::shared_ptr (but it can create other problems with dependencies)
- ensure you destroy classes in dependency order (usually it's enough to store them as members and ensure they go in correct order)
struct A {
MyObj obj; // constructed first, destriyed last
MyObj2 obj2{&obj}; // constructed last, destroyed first
};
class A {
public:
A();
private:
MyObj obj; // constructed first, destriyed last
MyObj2 obj2; // constructed last, destroyed first
};
A:A()
: obj2(&obj)
{}
Here if obj2 stores reference to obj, then it's completely safe, because obj2 will be always destroyed first. The order is the same in both cases, because of order of fields in the struct/class.
This has a potential to break:
class A {
public:
A();
private:
MyObj2 obj2;
MyObj obj;
};
A:A()
: obj2(&obj)
{}