문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top