I have a problem with c++ pointers
I’m a C# and VB.NET programmer, but I have converted to C++ recently, so I’m a C++ new newbie somehow
Now I’m writing a subtitle editor and I have two classes a subtitle Paragraph class containing a list of pointers to all of its lines
And a subtitle line class containing a pointer to its parent paragraph (to invoke a method in parent when line has changes )
In the subtitle paragraph class, when I delete the list of pointer to the sub lines they don’t get deleted
I tested this by trying to use the pointers after deleting them and call some functions and they work!
I also used “System Monitor” in Ubuntu to tell how much memory does my application use before and after allocating space for the pointers
and I found that it gets increased after allocating memory but the space doesn’t get freed after I delete the pointers
So I have a couple of questions:
1- can I have two classes each of which referencing to each other?
2- when I replace a pointer in one of the two classes with a reference does the same problem still exists
3- if I have two classes each of which referencing to each other how can I break this reference manually
I know I can use a shared pointer or weak pointer classes but I want to do it manually first
Here is a sample of my two classes to demonstrate the problem in my application
#include <iostream>
#include <stdio.h>
class B;
class A
{
public :
void setB(B *b){_b = b;cout << "set B" << endl;}
~A();
private:
B *_b;
};
class B
{
public :
void setA(A *a){_a = a;cout << "set A" << endl;}
~B(){cout <<"B is dieing" << endl;/*delete _a;*/}
private:
A *_a;
};
A::~A(){cout << "A is dieing" << endl;delete _b;}
int main()
{
getchar(); // two have some time to know how much memory does my application use before allocaing space for pointers
A *a = new A;
B *b = new B;
a->setB(b);
b->setA(a);
getchar();// two have some time to know how much memory does my application use after deallocaing the space
delete a;
delete b;
// but here,after deleting it, it's still there, not deleted! I can use it
a->setB(b);
getchar();
return 0;
}
thanks in advance
Yasser Sobhy
After having deleted an object, you could make the pointers point to NULL so you would not be able to use both of them anymore.
When you free a memory space in the heap, blocks are considered as free so they will be overwritten on any further memory allocation. But if not, you can still use it as you saw. But it is obviously not a good practice at all.