Error when delete object from vector

Started by
2 comments, last by prchakal 13 years, 4 months ago
Hi,

I have a vector of bullets:

static std::vector<boost::shared_ptr<Bullet>> *bullets;

But when i remove a bullet from vector with the code:

bullets->erase(std::find(bullets->begin(), bullets->end(), (boost::shared_ptr<Bullet>)this));

I get this error(see the image below):

http://www.prsolucoes.com/downloads/error_vector.png

What i do wrong?
Advertisement
You are casting "this" to a boost::shared_ptr<Bullet>. That is incredibly dangerous, do not cast something unless you are 200% sure of what you are doing.

You might want to research boost::shared_from_this, or write a custom comparator that compares the inner pointers, not the shared_ptr<> objects.
template<typename T>struct FindSharedPtr{private:   const T *ptr;public:   FindSharedPtr(const T *ptr) : ptr(ptr) {}   bool operator()(const boost::shared_ptr<T> &shared) const   {       T &ref = *shared;       return &ref == ptr;   }};// later...bullets.erase(std::find(bullets.begin(), bullets.end(), FindSharedPtr(this));



Better still, remove the static vector with automatic deregistration. There are superior designs.
Hi,

I have used the "shared_from_this()" from boost, but i receive an exception:

http://www.prsolucoes.com/downloads/error_boost.png

When i try:

Turret::Turret(float angle)
{
shared_from_this()->angle = angle;
initialize();
}


Im calling it from constructor
I solve the problem not using the function "shared_from_this" on constructor.

I use only on initilize method, and now i create and initialize the object like it:

boost::shared_ptr<Turret> turret1(new Turret());

turret1->initialize(0); //this is the method the contains "shared_from_this"

GameObjects::turrets->push_back(turret1);


Thanks.

The game is working now, deleting all fom memory.

This topic is closed to new replies.

Advertisement