Search code examples
c++vectorlinked-listdynamic-memory-allocation

c++ vector of objects, containing dynamically allocated memory - 'erase' does not work


I have a created a class 'Route' which stores a linked list. Objects of the 'Route' class are stored in vectors (and sometimes deleted).

Without a copy constructor/destructor/etc. the program works fine, but I want to avoid memory leaks, so I need a copy constructor/destructor etc. Since creating these, vector 'erase' seems to delete the wrong elements from the vector (ie, the last element, not the nth element). Sometimes elements get erased from vectors even though none should be deleted. Is there something wrong with my constructor/destructor/copy constructor? (Every time a Route object is copied, to be put on to a vector, an entirely new version of the linked list is created, using new memory - using the 'copyLinkedList' function).

`Route::Route(int destnAddr, MovePtr routeToDestn) : 
  destinationAddress(destnAddr){
    firstMove = copyLinkedList(routeToDestn);
}

Route::Route(const Route& _route){
  destinationAddress = _route.destinationAddress;
  firstMove = copyLinkedList(_route.firstMove);
}

Route& Route::operator=(const Route& _route){
  Route newRoute(_route);
  return newRoute;
}

Route::~Route(){
  MovePtr toDelete = firstMove;
  while(firstMove != NULL){
    firstMove = firstMove->next_move;
    delete toDelete;
    toDelete = firstMove;
  }
}

MovePtr Route::copyLinkedList(MovePtr listHead) {
  MovePtr newListHead = NULL;

  if (listHead == NULL){ 
      return newListHead; 
  }

  newListHead = new Move;
  newListHead->router_address = listHead->router_address;
  newListHead->next_move = copyLinkedList(listHead->next_move);
  return newListHead;
}`

Solution

  • What you're doing in operator= makes no sense whatsoever. You should assign the state of the parameter to the current object. Instead, you create a new object and return a dangling reference to it.

    Try to google for "assignment operator" or "special member functions" or "rule of three" for details.