I have two four classes:
- MainClass (the class where it all starts)
- XmlReader (a class used to parse an XML file)
- SerialPortSettings (contains information about the serial port read from the xml file, for example, baud rate, comport, etc.)
- SerialPortListener (refers to the SerialPortSettings object in its constructor)
MainClass has a method of reading things from an xml file. In this method, it first creates an XmlReader instance and gives it an xml file as a constructor parameter. This xmlReader should exist only inside this method:
XmlReader xmlReader (xmlFile);
xmlReader parses the xmlFile. MainClass accesses XML materials by invoking get methods in XmlReader . So far so good.
However, one of the XmlReader methods is a method that creates an object of the SerialPortSettings type based on the information read from the xml file:
SerialPortSettings* XmlReader::getSerialPortSettings() { .... // reading stuff from xml file return new SerialPortSettings(baudRate, dataBits, comport); }
This method is called from MainClass , and the return value is stored in a pointer:
SerialPortSettings* settings = xmlReader.getSerialPortSettings();
The next thing that MainClass does is create a SerialPortListener (which is a member variable that must exist before MainClass exits). SerialPortListener refers to the SerialPortSettings constructor in it:
m_serialPortListener = new SerialPortListener(*settings);
Therefore, SerialPortSettings must also exist before the MainClass exits, so I created this as a pointer.
So here is the key:
In the SerialPortListener destructor, I tried to remove the SerialPortSettings object:
SerialPortListener::~SerialPortListener() { delete &m_settings; }
Then, in the MainClass destructor , I deleted the SerialPortListener object:
MainClass::~MainClass() { delete m_serialPortListener; }
It fails. I get an error that I deleted something twice in the main class:
*** glibc detected *** ./ioserver: double free or corruption (out): 0x00860d80 ***
When I delete delete & m_settings from SerialPortListener, it works fine. But when do you need to delete a pointer? What to do right? I really want my xml-reader to create the SerialPortSettings - instand object, return all the information (baud rate, comport, etc.) to MainClass and create the SerialPortSettings object itself.