-2
class object
{
public:
    object(){}
    ~object(){}
};

int main()
{
    object *p = NULL;
    {
         object a;
         p = &a;
         if(p){
             cout << "not NULL\n";
         }
         else{
             cout << "NULL ptr\n";
         }
    }
    if(p){
        cout << "not NULL\n";
    }
    else{
        cout << "NULL ptr\n";
    }
    return 1;
}

result:

not NULL not NULL


I don't know why this result, I think it is "not NULL" and "NULL". When object's destructor was called, then p points to what? How does stack memory work?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
AI005
  • 51
  • 3
  • 2
    `p` doesn't _magically_ set itself to `nullptr` once `a` goes out of scope. – tkausl Nov 13 '19 at 16:19
  • Possible duplicate of [C++: Reference to "out of scope" object](https://stackoverflow.com/questions/9941502/c-reference-to-out-of-scope-object) – underscore_d Nov 13 '19 at 16:20
  • C++ provides great power but at the expense of great responsibility. Don't do silly things. If you do, don't expect logical results. – underscore_d Nov 13 '19 at 16:21

1 Answers1

0

When a is destroyed, p become a dangling pointer. It's a pointer that is not null, but still undefined behavior to dereference it.

That's because one dying object will not start to change values everywhere in the program. What happens if you have one hundread pointers to the dying object everywhere in the program? You can't just change all of their value to nullptr magically. If you want those pointer to become nullptr, you'll have to affect those value yourself.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141