Jump to content
  • Advertisement
too_many_stars

Managing pointers upon object destruction in C++

Recommended Posts

On 1/22/2019 at 2:26 PM, pcmaster said:

The troll manager might have a hash-map<Handle,Troll> style dictionary, in a naive implementation. Every time it's asked, it'll look into the hash-map and return nullptr if it doesn't find anything (or anything alive). And if it does find it, it can actually return a POINTER (!) but you must not store it for later use. Just use it and forget it. Next time, it might return a different pointer for the same handle, for example if it did some kind of defragmentation.

It is worst possible architrcture here. Becouse it move  lifetime managment expences from event that happends only once during throll lifetime to access, that happends every frame  for every warrior-throll pair. i.e. making O(n^2) task for every ftame from O(n) task that have to be perfoemed only once. It ever worse than using of weak_ptr that have same disadvantage, but have a O(1)  access time instead of hash that have O(1) in best case only.

Share this post


Link to post
Share on other sites
Advertisement

In my opinion, the way to do this is to not design your code in a way that has potentially hanging pointers. Manage the lifetime of objects so they predictably delete together. Don't store pointers to things you don't know the lifetime of. There are games where this is not possible but for most concepts it's easily doable. Back in the day, we used to write with a "no allocation during gameplay" rule.

In the case discussed, you don't need to store a pointer to the Troll, you probably don't even want to. Instead your AI should be tracking what it sees using its own internal representation, and updating this from the world each frame. This both avoids the problem of hanging pointers and allows separation of knowledge so that, for example, when the Troll disappears round a corner, your code can remember it went there and when it was last seen.

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

  • Advertisement
×

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!