Basically B is an object and A is an object manager, for each object created a new entry will be performed in m_myMap just in order to keep track of the number of objects and to be able to get a pointer of this object.
My question is: do I have to delete the pointers of B in m_myMap in A's destructor or will there be no memory leaks if m_myMap is automatically destroyed ?
A.h:
#ifndef A_H
#define A_H
#include "B.h"
class B;
class A
{
public:
A();
~A();
int addB(B* myBPointer);
private:
std::map<int,B*> m_myMap;
}
#endif
B.h:
#ifndef B_H
#define B_H
#include "A.h"
class A;
class B
{
public:
B(A* givenA);
~B();
private:
A *m_myA;
int m_id;
}
#enfif
B.cpp:
B::B(A* givenA)
{
m_myA = givenA;
m_id = m_myA->addB(this);
}
B::~B(){} // nothing here because m_myA is coming from another class and is destroyed in that class
A.cpp:
A::A();
A::~A()
{
for(std::map<int,B*>::iterator it = m_myMap.begin();it != m_myMap.end();++it)
delete it->second;// the program crashes
}
int A::addB(B* myBPointer)
{
m_myMap.insert(std::pair<int,B*>(m_myMap.size(),myBPointer));
return m_myMap.size()-1;
}
C.cpp and C.h:
#ifndef C_H
#define C_H
#include "A.h"
class C
{
public:
C();
void myFunction();
private:
A* my_A;
}
#endif
C::C()
{
my_A = new A;
}
void C::myFunction()
{
B myObject(my_A);
}