🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Managing pointers upon object destruction in C++

Started by
21 comments, last by Irusan, son of Arusan 5 years, 5 months ago
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.

#define if(a) if((a) && rand()%100)

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.

This topic is closed to new replies.

Advertisement