Jump to content

  • Log In with Google      Sign In   
  • Create Account


C++ vector of boost::weak_ptr troubles


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
10 replies to this topic

#1 chiranjivi   Members   -  Reputation: 197

Like
0Likes
Like

Posted 03 August 2013 - 07:48 PM

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.



Sponsor:

#2 AllEightUp   Moderators   -  Reputation: 4165

Like
3Likes
Like

Posted 03 August 2013 - 09:23 PM


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.



#3 belfegor   Crossbones+   -  Reputation: 2519

Like
0Likes
Like

Posted 04 August 2013 - 12:03 AM

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.


Edited by belfegor, 04 August 2013 - 12:06 AM.


#4 SyncViews   Members   -  Reputation: 319

Like
1Likes
Like

Posted 04 August 2013 - 02:35 AM

 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?


Edited by SyncViews, 04 August 2013 - 02:44 AM.


#5 belfegor   Crossbones+   -  Reputation: 2519

Like
0Likes
Like

Posted 04 August 2013 - 02:42 AM

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?


Edited by belfegor, 04 August 2013 - 02:42 AM.


#6 SyncViews   Members   -  Reputation: 319

Like
2Likes
Like

Posted 04 August 2013 - 04:40 AM



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.


Edited by SyncViews, 04 August 2013 - 04:42 AM.


#7 belfegor   Crossbones+   -  Reputation: 2519

Like
0Likes
Like

Posted 04 August 2013 - 05:04 AM

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

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


#8 chiranjivi   Members   -  Reputation: 197

Like
0Likes
Like

Posted 04 August 2013 - 07:17 AM

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.


Edited by chiranjivi, 04 August 2013 - 07:18 AM.


#9 chiranjivi   Members   -  Reputation: 197

Like
0Likes
Like

Posted 04 August 2013 - 07:19 AM

edit: how the hell did I post this twice



#10 SyncViews   Members   -  Reputation: 319

Like
1Likes
Like

Posted 04 August 2013 - 07:37 AM

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?


Edited by SyncViews, 04 August 2013 - 07:39 AM.


#11 AllEightUp   Moderators   -  Reputation: 4165

Like
1Likes
Like

Posted 04 August 2013 - 03:58 PM

AllEightUp, on 03 Aug 2013 - 10:23 PM, said:
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.

 

Ah, good, defining something within a condition is just a bad idea and scares me.. smile.png

 

Now, given the other information I can think of a couple things to look at:

 

1.  As others mentioned, if the call itself fails, check the caller is calling on a valid object.

 

2.  If the declaration of the function is "void set_as_target( boost::shared_ptr ptr )" then the failure could be during the pass by value of the shared_ptr itself which leads to a couple possibilities:

 

a) while the pointer may look valid, have you ensured a single source of the shared_ptr?  I.e. if you don't have "enable_shared_from_this" then you could have two raw pointers assigned into different shared_ptr's and they each keep separate ref counts.  So, in the case of pass by value, the copy constructor could be accessing the ref count of an object which was accidentally destroyed via a separate instance of a shared_ptr.  Hope this makes sense, shared_ptr's can be a bitch if you are not careful with how you create them and make copies.

 

b) even with enable_shared_from_this, you can still end up with different ref counts if you in one case you construct a smart_ptr from a raw pointer which is abstract and doesn't know about the actual derivative.  This is quite a bit more difficult to have happen but I've seen it once or twice with a goof.

 

 

Beyond those items, I think folks will need a bit more context to help too much further.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS