I have many classes inherited from the abstract base SysLaserBase. I add every laser to a list in the program (vector of pointers to the objects) as you see in the function addLaser(). This works perfectly fine, and it's totally working, and I can cycle through all the lasers I created and use their methods with no problems.
The problem happens then when I want to "remove" a laser from the system. I do this by comparing the address of the object with all the addresses in the vector of the base class's pointers. Is this legal? it's causing the program to crash some times. What's the alternative?
Please find here the code of the methods, and then an example of the call that causes the crash. Do you find anything wrong in the code of removeLaser()? why does the whole system act crazy after the removal of a single laser?
the vector involved is in the base class's body:
std::vector<SysLaserBase<T>*> lasers;
And the add and remove methods:
template <typename T>
void SysSystemBase<T>::addLaser(const SysLaserBase<T> &src)
{
bool alreadyThere = 0;
for(unsigned long i = 0; i < lasers.size(); i++)
{
if(&src == lasers[i])
{
alreadyThere = 1;
break;
}
}
if(!alreadyThere)
{
lasers.push_back(const_cast<SysLaserBase<T>*>(&src));
}
signalsOut.resize(lasers.size());
}
template <typename T>
void SysSystemBase<T>::removeLaser(const SysLaserBase<T> &src)
{
for(typename std::vector<SysLaserBase<T>*>::iterator it = lasers.begin(); it != lasers.end(); ++it)
{
if((*it) == &src)
{
lasers.erase(it);
}
}
signalsOut.resize(lasers.size());
}
Call of this code:
sys.addLaser(las0);
sys.addLaser(las1);
sys.addLaser(las2);
sys.removeLaser(las0); //removes the laser, but cycling through the lasers through the vector of base class causes a crash
sys.removeLaser(las1);
sys.removeLaser(las2); //crashes the program immediately after this call
Thank you for any efforts :-)
Thank you for the replies. According to your replies I have changed removeLaser() to this:
template <typename T>
void SysSystemBase<T>::removeLaser(const SysLaserBase<T> &src)
{
for(typename std::vector<SysLaserBase<T>*>::iterator it = lasers.begin(); it != lasers.end(); ++it)
{
if((*it) == &src)
{
lasers.erase(it);
break;
}
}
signalsOut.resize(lasers.size());
}
It's OK now. Thanks :-)