In a C++ program I define several data structures and the class DataClass.
Content of DataClass.h :
typedef struct
{
int ta;
long tb;
} DataTrgType;
typedef std::vector <DataTrgType> TRG_Type;
typedef struct
{
int a;
long b;
bool c;
TRG_Type* TRG;
} DataType;
class DataClass
{
private:
DataType* myData;
std::vector <DataType> myDatas;
DataTrgType* dataTRG;
public:
DataClass(std::string pLogFile);
virtual ~DataClass();
void createData();
void setA (int a);
void setB (long b);
void setC (bool c);
void addData();
void createDataTRG();
void setTA (int ta);
void setTB (long tb);
void addDataTRG ();
};
DataClass.cpp :
void DataClass::createData()
{
if (myData != NULL)
{
delete myData;
myData = NULL;
}
myData = new DataType;
}
void DataClass::addData()
{
if (myData != NULL)
{
myDatas.push_back(*myData);
delete myData;
myData = NULL;
}
}
void DataClass::createDataTRG()
{
if (dataTRG != NULL)
{
delete dataTRG;
dataTRG = NULL;
}
dataTRG = new DataTrgType;
}
void DataClass::addDataTRG ()
{
if (dataTRG != NULL)
{
(*(myData->TRG)).push_back(*dataTRG);
delete dataTRG;
dataTRG = NULL;
}
}
In main I run this code:
DataClass classObj;
classObj.createData();
classObj.setA (11);
classObj.setB (12);
classObj.setC(false);
classObj.createDataTRG();
classObj.setTA (110);
classObj.setTB (112);
classObj.adddataTRG ();
classObj.createDataTRG();
classObj.setTA (105);
classObj.setTB (107);
classObj.adddataTRG ();
classObj.addData();
classObj.createData();
classObj.setA (21);
classObj.setB (22);
classObj.setC(false);
classObj.createdataTRG();
classObj.setTA (210);
classObj.setTB (212);
classObj.adddataTRG ();
classObj.addData();
In the program I correctly display the content of these data structures with:
typename std::vector <DataType> :: iterator it;
typename std::vector <DataTrgType> :: iterator itTrg;
std::cout << "myDatas has " << myDatas.size() << " elements" << std::endl;
for (it = myDatas.begin(); it != myDatas.end(); ++it)
{
std::cout << "Data.a = " << (*it).a << " Data.b = " << (*it).b << std::endl;
for (itTrg = (*it).TRG->begin(); itTrg != (*it).TRG->end(); ++itTrg)
{
std::cout << " Trg.ta = " << (*itTrg).ta << " Trg.tb = " << (*itTrg).tb) << std::endl;
}
}
In the destructor of the class I want to release the memory.
I have tried with this code:
DataClass::~DataClass()
{
typename std::vector <DataType> :: iterator it;
typename std::vector <DataTrgType> :: iterator itTrg;
for (it = myDatas.begin(); it != myDatas.end(); ++it)
{
for (itTrg = (*it).TRG->begin(); itTrg != (*it).TRG->end(); ++itTrg)
{
delete (*itTrg);
}
delete it;
}
}
But it does not compile, showing numerous errors in the destructor.
I have done some other test, but it doesn't compile either and I can't find the correct code to free the memory.
for (int i=0; i<myDatas.size(); i++)
delete (myDatas[i]);
myDatas.clear();
Any help or suggestion is appreciated.