1

I have some very interesting code snippets. When I delete a object, its value become zero, but the object pointer can still be manipulated, is this wierd?

#include <iostream>
#include <vector>

using namespace std;

class B
{
public:
  vector<double> vec;
};

class A 
{ 
public:
  B b;
};

int main()
{
  A* a = new A();

  a->b.vec.push_back(1);
  a->b.vec.push_back(2);

  A* a1;

  delete a;

  cout << "before" << endl;
  a1= a;

  cout << a1->b.vec[0] << endl;
  cout << "after" << endl;

  return 0;
}

output:

before
0
after

After I delete a, its value become zero, but it still can be referenced? I don't know why?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jack Chin
  • 525
  • 4
  • 12
  • Accessing the destroyed object is undefined behavior. You were not lucky becoz the program ran without error. – cbel Apr 03 '14 at 05:37

2 Answers2

4

What you're doing results in undefined behavior, meaning that anything can happen. Calling delete a ends the lifetime of the object pointed at by a and releases the memory back to the free store (the C++ spec's term for what we typically call the heap). At that point, accessing the memory results in undefined behavior. In your case, this coincidentally happens to print out the old values, but there's no reason that this is guaranteed. You could theoretically have a compliant C++ implementation that would format your hard drive if you ran this code.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
3

After I delete a, its value become zero, but it still can be referenced? I don't know why?

No, once you delete it, it would not assign a with null.If you want to do that, you need to do it explicitly.

delete a;
a = NULL;

You should not use the a after calling delete on it. There would be undefined behaviour and as pointer is dangling. Do not ever use it.

Mantosh Kumar
  • 5,659
  • 3
  • 24
  • 48