C ++ - representation of property rights through pointers

There are three classes in my game engine: EntityCharacter, EntityVehicle and EntityVehicleSeat.

enter image description here

EntityVehicle contains place objects with pointers to EntityCharacter instances. If the entity pointer of an object of an object of a place of an object is a null pointer, no symbol is placed on this particular seating object. Instances of the EntityCharacter class also have pointers to the placement of objects that indicate whether these symbol objects are in some vehicles or not.

In other words, an instance of EntityCharacter-class has a pointer to EntityVehicleSeat and vice versa:

EntityCharacter -> EntityVehicleSeat EntityCharacter <- EntityVehicleSeat 

Thus, we can verify this ownership with a symbolic and vehicle.

It would be easy to point to pointers to point to each other, but there is one problem - if another object falls out of scope, we end up with an invalid pointer.

enter image description here

How can you imagine this type of property in a complex way? How can I tell another object that another object no longer exists?

+6
source share
1 answer

Object-to-object relationship management, including bidirectional relationships, is where destructors become useful. You can fix the dangling pointer problem as follows:

 ~EntityCharacter() { // Do some other cleanup... ... if (seatPtr) { assert(seatPtr->characterPtr == this); // That my seat! seatPtr->characterPtr = NULL; } } ~ EntityVehicleSeat() { // Do some other cleanup... ... if (characterPtr) { assert(characterPtr->seatPtr == this); // That my character! characterPtr->seatPtr = NULL; } } 

One of the problems with this approach is concurrency: if a place and a character can be deleted simultaneously from different threads, you will need to synchronize the deletions.

+4
source

All Articles