C++ vector of boost::weak_ptr troubles

Started by
9 comments, last by GameDev.net 10 years, 8 months ago

I have a game that has a number of ships in space. The ships exist in the gameworld as boost::shared_ptr<Ship>. These ships can attack one another. The Ship class has a boost::weak_ptr<Ship> called target, which holds a reference to whatever it's currently firing at, and it also has a vector of weak_ptr<Ship> called aggro_vector. The aggro vector records all ships that have attacked this Ship, so that when it kills its current target, it can consult its aggro vector to see which other ships it is currently in combat with, and pick a new target.

This is the Ship class, sanitised:


class Ship
{
    public:
    Ship (int x, int y);

    boost::weak_ptr<Ship> target;
    std::vector< boost::weak_ptr<Ship> > aggro_vector;

    void determine_next_target();
    void set_as_target (boost::shared_ptr<Ship> next_target);
}

What I'm having trouble with is getting the Ship to correctly look through its aggro_vector and choose a new target.

Here is the function that picks the next target from the aggro vector. It iterates through all the weak_ptrs, and if .lock() successfully returns a shared_ptr, it hands this shared_ptr off to the member function that registers the next target. Otherwise the weak_ptr refers to a ship that has since been destroyed and is removed from the aggro vector:


void Ship::determine_next_target()
{
    std::vector< boost::weak_ptr<Ship> >::iterator it = aggro_vector.begin();
    while(it != aggro_vector.end()) {
        if (boost::shared_ptr<Ship> this_ship = (*it).lock()) {
            set_as_target(this_ship);
            ++it;
        } else {
            it = aggro_vector.erase(it);
        }
    }
}

When this code is compiled and run, it crashes at the line set_as_target(this_ship). If this line is commented out, the remainder of the code works as it should (although obviously the determine_next_target() function now does nothing other than remove expired weak_ptrs).

To be clear, the set_as_target(boost::shared_ptr<Ship>) function works fine and is called from a bunch of other places in the code with no problem. It doesn't appear to be that function, but rather the fact that I'm attempting to call that function in this way.

Why am I having problems passing a shared_ptr to an outside function in this fashion? Is there something about iterating over a vector of weak_ptr that I'm missing, or am I just failing to grasp, in the broader sense, some aspect of how these pointers should be used?

Thanks in advance for any help.

Advertisement


void Ship::determine_next_target()
{
std::vector< boost::weak_ptr >::iterator it = aggro_vector.begin();
while(it != aggro_vector.end()) {
if (boost::shared_ptr this_ship = (*it).lock()) {
set_as_target(this_ship);
++it;
} else {
it = aggro_vector.erase(it);
}
}
}

My first guess is some odd behavior with scoping. Basically I don't remember for sure the scope rule but I bet if you change the code as follows, it may at least give you some better information on what the problem is:

void Ship::determine_next_target()
{
std::vector< boost::weak_ptr >::iterator it = aggro_vector.begin();
while(it != aggro_vector.end()) {
boost::shared_ptr this_ship( (*it).lock() );
if ( this_ship ) {
set_as_target(this_ship);
++it;
} else {
it = aggro_vector.erase(it);
}
}
}

Creating a variable inside the if condition is just a really ugly and bad thing to do. While this may not actually fix things, at least you should be able to double check the value properly.

shared_ptr might be emtpy, try this:


void Ship::determine_next_target()
{
std::vector< boost::weak_ptr >::iterator it = aggro_vector.begin();
while(it != aggro_vector.end()) {
if(!(*it).expired()) {
boost::shared_ptr this_ship( (*it).lock() );
set_as_target(this_ship);
++it;
} else {
it = aggro_vector.erase(it);
}
}
}

I am not sure if boost weak_ptr have expired method, i am using std weak_ptr.

Better yet put a breakpoint and check vector content.

Where exactly does it crash? In the called function, on the function call itself, next loop iteration? If the set_as_target method can in some way result in aggro_vector being modified, your iterator will be invalidated.

If using MSVC in debug it may tell you this with their iterator debugging stuff, but even for other compilers a debug build might give you a more specific crash point if your not already using debug, and you can look at the variable values at that point to see if somthing looks wrong (e.g. invalid pointer or iterator).

shared_ptr might be emtpy, try this:


void Ship::determine_next_target()
{
    std::vector< boost::weak_ptr >::iterator it = aggro_vector.begin();
    while(it != aggro_vector.end()) {
        if(!(*it).expired()) {
            //Some other thread owned the last shared_ptr and destroyed it between these lines
            //this_ship will be null
            boost::shared_ptr this_ship( (*it).lock() );
            set_as_target(this_ship);
            ++it;
        } else {
            it = aggro_vector.erase(it);
        }
    }
}

I am not sure if boost weak_ptr have expired method, i am using std weak_ptr.

Better yet put a breakpoint and check vector content.

Is it really generally a good idea to use expired?

Now when i look better at your code. isn't iterator "invalidated" after call to erase?

Try this instead (without iterator):


auto& av = aggro_vector;
for(std::size_t i = 0; i < av.size(); ++i)
{
    if(!av[i].expired())
    {
        boost::shared_ptr this_ship(av[i].lock());
         ...
    }
    else
    {
        std::swap( av[i--], av.back() );
         av.pop_back();
    }
}

Is it really generally a good idea to use expired?

Why not?



Like
0Likes 1Likes
Like

Posted Today, 09:42 AM

Now when i look better at your code. isn't iterator "invalidated" after call to erase?

std::vector::erase returns an iterator to the element after the one erased, "it = aggro_vector.erase(it);", and the it++ is in the don't erase condition, so the loop will always advance to the next element.


Quote


Is it really generally a good idea to use expired?

Why not?

See my comment. If at some point you have multiple threads having a shared_ptr to something for any reason, checking expired does not guarantee lock will succeed leaving you will a null pointer anyway. Additionally even without multiple threads, if you have stuff between expired and lock (e.g. another function call) you might indirectly kill the object and lock will also return null then. It is safe in this case, I was just wondering if it is best to avoid that pattern, and always just use lock and check for not null on the shared_ptr.

Yeah, might do without expired since shared_ptr has convert/cast operator bool so:

shared_ptr<ship> me(wp.lock())
if(me)
 ...

Thanks everyone for your responses. I am still struggling with this, unfortunately.

My first guess is some odd behavior with scoping. Basically I don't remember for sure the scope rule but I bet if you change the code as follows, it may at least give you some better information on what the problem is:

void Ship::determine_next_target()
{
    std::vector< boost::weak_ptr >::iterator it = aggro_vector.begin();
    while(it != aggro_vector.end()) {
        boost::shared_ptr this_ship( (*it).lock() );
        if ( this_ship ) {
            set_as_target(this_ship);
            ++it;
        } else {
            it = aggro_vector.erase(it);
        }
    }
}

That's actually the exact code I was using to begin with; I just simplified it for the purpose of posting the thread! It doesn't work in the same way that the original code doesn't work.

shared_ptr might be emtpy,

It isn't, I stuck a call to cout in the if {} block that checks some properties of the object like its XY position (std::cout<<this_ship->x<<":"<<this_ship->y<<std::endl;) and it returned the correct values, so shared_ptr is functioning properly and is pointing at a valid object.

Where exactly does it crash? In the called function, on the function call itself, next loop iteration?

On the function call itself. I don't really know what to make of that.

edit: how the hell did I post this twice

If a function call itself crashes, the only thing I can think of is if using a function pointer or virtual function, and the pointer/this is null/invalid which you do not appear to be doing there. Even if you had a corrupted shared_ptr, I would expect a crash in the copy constructor.

You testing this on a debug build so that stuff doesn't get inlined/hidden?

This topic is closed to new replies.

Advertisement