c++ - Deleting a pointer in a list causing memory leak -


so have program (a game question in c++ question) has character class. simplified code of classes/methods in question

eg

basecharacter.h

class basecharacter {     basecharacter();     ~basecharacter();      weapon* m_currentweapon;     doublelinkedlist<weapon*> m_weaponsheld; } 

basecharacter.cpp

basecharacter::basecharacter() {     m_currentweapon = new weapon();     m_weaponsheld.insert(m_currentweapon); } basecharacter::~basecharacter() {     m_weaponsheld.clear(); } 

the idea of class every character starts 1 starting weapon (which added list of weapons) , can hold mulitple weapons (which when created stored through list)

the list functions insert , clear this

template <class c> inline void doublelinkedlist<c>::insert(const c &data) {     linkedlistnode<c>* node = new linkedlistnode<c>(data);      if(m_tail)     {         m_tail->setnext(node);         node->setprevious(m_tail);         m_tail = node;     }     else     {         m_head = node;         m_tail = node;     }   listsize++; }   template <class c> inline void doublelinkedlist<c>::clear() {     linkedlistnode<c>* entry = m_head;      while (entry)     {         linkedlistnode<c>* release = entry;         entry = entry->getnext();         delete release;     }      listsize = 0;     m_head = 0;     m_tail = 0; } 

the issue having when basecharacters class deleted, destructor called , memory leak occurs.

i don't understand (well have small idea - think deleting pointer pointer when clear list rather object stored in list) why weapon classes destructor isn't called when lists clear() function called in basecharacters destructor.

can show me logic error in cleaning list , weapons of character?

are having memory-leak or corruption? think of corruption because delete weapon , in case second player has same pointer weapon doublelinkedlist<c>::clear tries free memory again of same object.

removing delete might work here that's not final solution. has own actual weapon - game-engine creates asset , assigns them individual characters. why characters share same instance? shouldn't each player own own copy of weapon? expect weapon has individual ammo count , shouldn't shared :)

therefore each player should own own weapon.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -