-1

As it says here: How to use delete with a variable pointed to by two pointers? one can only delete once, then all pointers won't work, but the code below:

#include<iostream>
using namespace std;

int main(){
    string * str1 = new string("abc");
    string * str2 = str1;
    cout<< *str2 <<endl;
    delete str1;
    str1 = NULL;
    cout<< *str2<<endl;
}

the output is:

abc
abc

so, what's the matter?

Community
  • 1
  • 1
expoter
  • 1,622
  • 17
  • 34

2 Answers2

1

Once you have deleted a pointer, accessing it is undefined behavior and may print old contents sometimes, may crash sometimes or may do something beyond thinking some other time.

To handle a case of deleting shared pointer, use std::shared_ptr or similar reference counting manager wrapper instead of naked pointers.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
0

One of the outcomes of undefined behavior is that is might seem to work. And dereferencing a pointer to a destructed object (like you do with cout<< *str2<<endl;) is undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621