Sign in to follow this  
prchakal

Error when delete object from vector

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this