-2

I want to test what delete in c++ can do so wrote the following:

#include <iostream>
#include <vector>

using namespace std;

class A{
public:
  A(string s):a(s){}
  string getS(){
    return a;
  }
private:
  string a;
};

class B{
public:
  B(string str):s(str){}
  void setV(A a){
    v.push_back(a);
  }
  string getS(){
    return s;
  }
private:
  vector<A> v;
  string s;
};

int main(){
  A a("abc");
  B* b = new B("cba");
  b->setV(a);
  cout<<b->getS()<<endl;
  cout<<a.getS()<<endl;
  delete b;
  cout<<b->getS()<<endl;
  cout<<a.getS()<<endl;
  return 0;
}

And I still got the following output:

cba
abc
cba 
abc

looks like I can still get access the memory for both a and b? So my question would be 1.Why do I have access to b, since I have called delete on it? 2.Why do I have access to a, since b's destructor is called so the memory of vector containing a should be free?

Cheers

woodybird
  • 135
  • 2
  • 8
  • 1
    Duplicate question. You're invoking "Undefined behavior" by accessing deleted memory. – John3136 Aug 04 '15 at 03:01
  • 3
    Undefined behavior is undefined. You're not physically removing the bytes from your computer - you're just relinquishing ownership. – Drew Dormann Aug 04 '15 at 03:01

2 Answers2

2

The free function does not clear or zero out memory. It only makes it a free block that is ready to be malloc'ed by the memory manager.

The pointers and structures all hold the same values, and when referenced will create undefined behavior. Either throwing an exception/error or retrieving the information inside.

The Brofessor
  • 1,008
  • 6
  • 15
1

1.Why do I have access to b, since I have called delete on it?

It is Undefined Behavior, so anything is possible. It may work, may not, may get an error, a segment fault, may crash, and so on.

2.Why do I have access to a, since b's destructor is called so the memory of vector containing a should be free?

a was copied when you call b->setV(a);, so the vector in b has nothing to do with a.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405