I have test the following code
#include <iostream>
using namespace std;
class A
{
public:
int aa;
};
int main()
{
A *a = new A;
a->aa = 55;
A *b = new A;
b = a;
b->aa = 555;
delete b;
b= NULL;
cout<<a->aa<<endl;
delete a;
a=NULL;
return 0;
}
it has neither error nor warning when compiling but has error when executing.
after changing the main function to:
A *a = new A;
a->aa = 55;
cout<<a->aa<<endl;
A *b = new A;
b = a;
b->aa = 555;
cout<<a->aa<<endl;
delete b;
it worked as i expected.
my questions are:
1, why a cannot be deleted in the later code since once delete a, there is some error when executing although the right result can be printed.
2, why the first code is totally wrong.
absolutely. i just found the reason is a and b are both pointing to the same address where an object of A is stored. delete method in c++ deletes the content pointed by the pointer. after deleting b, the content at the address is removed. therefore, when the compiler tries to delete a, it will notice that the content is not valid anymore, thus reports an error.
absolutely. i just found the reason is a and b are both pointing to the same address where an object of A is stored. delete method in c++ deletes the content pointed by the pointer. after deleting b, the content at the address is removed. therefore, when the compiler tries to delete a, it will notice that the content is not valid anymore, thus reports an error.