Alexander Yin
Junior Member level 2
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.
thank you.
#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.
thank you.