• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
chiranjivi

C++ vector of boost::weak_ptr troubles

10 posts in this topic

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

 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
1

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites


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
2

Share this post


Link to post
Share on other sites

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

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

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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
1

Share this post


Link to post
Share on other sites

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.

1

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  
Followers 0