Jump to content
  • Advertisement
Sign in to follow this  
prchakal

Error when delete object from vector

This topic is 2774 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!