As stated in the question, if I have a class with a member that is a normal pointer( not dynamically allocated), do I need to write a destructor that delete the pointer? or the synthesized one would do its job and delete the pointer for me?
And while you are at this, could you guys please take a look at the code below
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
usingnamespace std;
int main()
{
int *a;
{
int b = 0;
a = &b;
}
cout << *a;
}
In this code, I had a pointer 'a', and I initialized an int object 'b' inside a sub-block and assigned 'a' to store the address of 'b' and then went out of the sub-block, and then dereferenced 'a' and printed it out, so I thought that the value being printed out should be a garbage value since the when the program went out of the sub-block, 'a' was still holding the address of 'b' but 'b' would have been destroyed, so the derefencced value of 'a' should be some random value that's currently stored in the address, but on the contrary, the printed value was still 0. Why?
Could you guys help me out here. I'd really appreciate it.
What does the pointer point to, if not to something that's dynamically allocated?
That code's behavior is undefined. Maybe garbage will be printed, maybe zero will be printed, maybe the program will crash, maybe the system will crash.
if I have a class with a member that is a normal pointer( not dynamically allocated), do I need to write a destructor that delete the pointer? No, when you "delete" a pointer you are deallocating the allocated memory.