In my game engine, there are three classes: EntityCharacter, EntityVehicle and EntityVehicleSeat.
EntityVehicle contains seat objects with pointers to instances of EntityCharacter. If seat object's target character entity pointer is a null pointer, no character is sitting on that specific seat object. EntityCharacter-class instances have also pointers to seat objects, indicating, whether these character entities are sitting in some vehicles or not.
In other words, EntityCharacter-class instance has a pointer to EntityVehicleSeat and the other way around:
EntityCharacter -> EntityVehicleSeat
EntityCharacter <- EntityVehicleSeat
This way we can check this ownership via both character and vehicle entity.
It would be simple to set pointers to point to each other, but there's one problem - if the other object falls out of scope, we end up having an invalid pointer in the remaining object.
How can one represent this kind of ownership sophisticatedly? How can the other object be informed about the fact that the other object no longer exists?
Managing object-to-object relationships, including bidirectional ones, is where destructors become helpful. You can eliminate the problem of dangling pointers like this:
~EntityCharacter() {
// Do some other cleanup...
...
if (seatPtr) {
assert(seatPtr->characterPtr == this); // That's my seat!
seatPtr->characterPtr = NULL;
}
}
~ EntityVehicleSeat() {
// Do some other cleanup...
...
if (characterPtr) {
assert(characterPtr->seatPtr == this); // That's my character!
characterPtr->seatPtr = NULL;
}
}
One problem with this approach is concurrency: if a seat and a character can be deleted simultaneously from different threads, you would need to synchronize deletions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With