Is this the correct practice with UObjects and smart pointers?
it's hard to find some documentation for this use case, and it's not yet very clear when to choose to use the various shared pointers, this is why I ask here if you think I did the things right:
I have a class UBBTeam inheriting from UObject, which has a reference to an other team, and holds a static array of weak pointers to some players (ABBCharacter). Each ABBCharacter is spawned regularly in the game mode. Moreover, each ABBCharacter holds a reference to another ABBCharacter, and a reference to his owning team. The owner of the teams is my ABBGameMode, which holds them in a static array of shared pointer.
Here are the interesting excerpts of the classes, where I have put in comments my various questions :
ABBMatchGameMode class declaration
ABBMatchGameMode class implementation
UBBTeam class declaration:
UBBTeam class implementation:
ABBCharacter class declaration:
ABBCharacter class implementation:
What do you think?
In the shooter game, I could see:
Does this mean that it is converted automatically to smart pointers under the hood?
asked Apr 02 '14 at 02:31 PM in C++ Programming
You don't want to use TSharedPtr/TSharedRef/TWeakPtr with UObjects, those are designed for non UObjects.
UObjects use a garbage collection system. By declaring UPROPERTY() that essentially lets the garbage collection system know about that reference. If you declare just a UObject *, that is a Hard reference, which means that the referenced object will not be freed as long as their is a chain of references from the Root to that object. Here's an overview of the basics: https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Objects/Optimizations/index.html
So, if you want to reference a UObject, but don't want it to be a Hard reference that keeps it from being garbage collected, you then use TWeakObjectPtr. This will automatically be set to NULL when the referenced object is deleted, but it won't stop that object from getting deleted if no other references to it exist. This is useful for things like UI where you want to know about the state of an object, but can gracefully handle it going away when it dies.
answered Apr 03 '14 at 08:38 PM
[Epic]Ben Zeigler STAFF
Follow this question
Once you sign in you will be able to subscribe for any updates here