c++ - Vector with custom objects: crash when I want to use one received with .at method -


i have class named cconfig, i'm creating new object:

std::vector< cconfig > docs;  cconfig newfile( "somefile.xml", "root" ); printf("%s", newfile.gettagvalue( "servername" )); // works docs.push_back( newfile ); 

when i'm getting object .at method

cconfig file = docs.at(0); printf("%s", file.gettagvalue( "servername" )); // crashes 

where's problem?

(im sorry if formatting wrong don't use javascript because bandwidth ended , max speed 1kb/s i'll try fix later)

cconfig.h:

class cconfig {     tixmldocument       m_doc;     tixmlelement*       m_proot;     bool                m_bisloaded;  public:                     cconfig                     ( void ) {};                     cconfig                     ( const char * pszfilename, const char * pszrootname );                     ~cconfig                    ( void ) {};  const char*         gettagvalue                 ( const char * psztagname ); const char*         gettagattribute             ( const char * psztagname, const char * pszattributename ); tixmlelement*       getrootelement              ( void )    { return m_proot; }; bool                isavailable                 ( void )    { return m_bisloaded; }; }; 

cconfig.cpp

#include "cconfig.h"  cconfig::cconfig( const char * pszfilename, const char * pszrootname ) {     m_bisloaded = m_doc.loadfile( pszfilename );     if( m_bisloaded )         m_proot = m_doc.firstchildelement( pszrootname ); }  const char * cconfig::gettagvalue( const char * psztagname ) {     if( m_bisloaded && m_proot )     {         tixmlelement * element = m_proot->firstchildelement( psztagname );         if( element )             return element->gettext();     } }  const char * cconfig::gettagattribute( const char * psztagname, const char * pszattributename ) {     if( m_bisloaded && m_proot )     {         tixmlelement * element = m_proot->firstchildelement( psztagname );         if( element )             return element->attribute( pszattributename );     } } 

i'm using tinyxml

your issue pointers old memory. when add item array, copied. later leave scope , original destroyed, ask pointer in copy pointing? still first (now deleted) object's memory. uh-oh.

the simplest fix (while avoiding large copy operations) make m_doc shared pointer (available in standard in c++11, or via boost in c++03). handle rule-of-3 wise. , because underlying memory won't move, m_proot remain valid until last copy has been deleted.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -