It's my first time posting so I do apologize if I've messed up in anyway or made anything more difficult than it should be.
Here's my issue:
I'm trying to erase data from a vector of boost::shared_ptr
nodes, nodes being a class.
In one part of my code, erasing an element from a vector known as openList works fine.
In another part of my code, erasing an element from a vector known as movingObjectsList, doesn't want to work. It gives prompts me with _block_type_is_valid(phead- nblockuse).
I've tried clear()
, popback()
and erase()
and all of them cause the same problem. I can add what I like to movingObjectsList
without any errors and swap the data it holds with other vectors, but I'm unable to delete any of the data.
I think I've ruled out it being an issue with the node destructor because I have the same issue when I use Ints instead of nodes, and also the openList
is able to erase elements.
This is how it's declared in the header.
vector<boost::shared_ptr <node>> movingObjectsList;
This is the relevant code in the cpp
grid::grid()
{
movingObjectsList = vector<boost::shared_ptr<node>>();
}
void grid::createGrid(){
boost::shared_ptr<node> movingObject = boost::shared_ptr<node> (&nodes[8][8]);
movingObjectsList.push_back(movingObject);
}
void grid::movingObjects()
{
movingObjectsList.erase(movingObjectsList.begin());
}
This is the simplest form I've cut it down to, only concerning movingObjectsList. Without the erase function, it works fine.
OK, mistake in what a shared pointer does.
A Shared pointer takes full ownership of a pointer. When that pointer goes out of scope, it'll delete that pointer.
You are inializsing the nodes as an node [8][]
. Your pointer is an address in this 2D array! When you need to call delete (which'll get called when your shared_ptr goes out of scope i.e. whenever you remove elements from the vector), you are essentially calling delete nodes[i][j]
, which you'd expect to barf.
Just use references in this case (Node&), which will be perfectly valid and work just fine.