C++ vector of boost::weak_ptr troubles

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

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.

This topic is closed to new replies.

Advertisement