c++ - Question about deleting a pointer. Which class should it be deleted from? -


i have 2 4 classes:

  • mainclass (class things start)
  • xmlreader (class used parse xml file)
  • serialportsettings (holds info serial port read xml-file, e.g. baud rate, comport etc)
  • serialportlistener (takes reference serialportsettings object in constructor)

mainclass has method read things xml-file. in method, first creates instance of xmlreader , gives xml-file constructor parameter. xmlreader need exist within method:

xmlreader xmlreader (xmlfile); 

the xmlreader parsers xmlfile. mainclass gets access xml-stuff calling get-methods in xmlreader. far good.

however, 1 of methods xmlreader offers, method creates object of type serialportsettings based on information read xml-file:

serialportsettings* xmlreader::getserialportsettings() {   .... // reading stuff xml file   return new serialportsettings(baudrate, databits, comport); } 

this method called mainclass , return value stored in pointer:

serialportsettings* settings = xmlreader.getserialportsettings(); 

the next thing mainclass create serialportlistener (which member-variable has exist until mainclass exited). serialportlistener takes reference serialportsettings in it's constructor:

m_serialportlistener = new serialportlistener(*settings); 

hence serialportsettings has exist until mainclass exits, therefore have created pointer.

so here clue:

in serialportlistener destructor tried delete serialportsettings-object:

serialportlistener::~serialportlistener() {   delete &m_settings; } 

then in mainclass destructor deleted serialportlistener-object:

mainclass::~mainclass() {   delete m_serialportlistener; }  

this fails. error saying deleted twice in main-class:

*** glibc detected *** ./ioserver: double free or corruption (out): 0x00860d80 *** 

when remove delete &m_settings serialportlistener, works fine. when should pointer deleted? correct thing do? want xml-reader create serialportsettings - object, insted of returning of info (baud rate, comport etc) mainclass , create serialportsettings object itself.

a solution let xmlreader::getserialportsettings return serialportsettings value.

let compiler optimization.

but need handle pointer lifetimes, use smart pointers, such std::auto_ptr or boost::shared_ptr. key idea define ownership. owner (which in case of boost::shared_ptr collection of smart pointers referring object) responsible deleting – no-one else.

cheers & hth.,


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -