Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Representing ownership via pointers

In my game engine, there are three classes: EntityCharacter, EntityVehicle and EntityVehicleSeat.

enter image description here

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.

enter image description here

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?

like image 619
Helixirr Avatar asked Mar 31 '13 10:03

Helixirr


1 Answers

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.

like image 88
Sergey Kalinichenko Avatar answered Sep 30 '22 00:09

Sergey Kalinichenko