TArray of TSharedRef validity

Hello.

Would as of 4.27 a TArray of TSharedRef automatically reflect referenced objects being destroyed by reducing number of elements or produce errors instead?

as in, if I made an array of shared references and iterate over it, is it possible that I get to invalid ones? or if it’s a bad idea, are there similar alternatives, maybe TSet or some other clean way to do it instead of additional manager?

The purpose I need it for is that I need to produce some arbitrary actors managed by another one, of a certain dynamic quantity, only local (not replicated over nets). Ideally if this was a valid solution I don’t need a manager, I just decided to ask maybe more experienced coders.

Shared pointers in Unreal Engine are made for objects outside the UObject system. If you want to use this TArray with actors, shared pointers should not be used. You want to use TObjectPtr. Yes, they will be null if you destroy any of the actors that are stored in these TObjectPtr’s.

You can use the actor’s OnDestroyed event to be notified when to remove an actor from your list when they are destroyed.

I’m not entirely sure what I am doing wrong but I get
“42:9: e[0me[0;1;31merror: e[0me[1muse of undeclared identifier 'TObjectPtr’e[0m
CompilerResultsLog: TArray<TObjectPtr> Arrows;”
and couldn’t find much info about it in 4.27

and, obviously “42:9: e[0me[0;1;31merror: e[0me[1muse of undeclared identifier 'TObjectPtr’e[0m
CompilerResultsLog: TArray<TObjectPtr< ABeamArrow>> Arrows;” tried that first

“use of undeclared identifier”, missing header include or incorrect usage.

TArray<TObjectPtr<AActor>> Test;

Thought TObjectPtr was actually UE5

Always use pointers with UObjects. (UObject* Test = nullptr) or its TObjectPtr variant.

The garbage collector automatically nulls these pointers when it collects the garbage objects. You can easily check them for nullptr or call IsValid. You want to avoid working with references that can become invalid (undefined behavior).

Arrays do not shrink automatically when pointers inside them null.

outside pointers to elements inside an array become invalid when elements are added / removed in array.

You should create an array of uobject pointers on the manager class. When you want to remove one of those uobjects, remove them through the manager so that the element is removed from its array before it starts to be destroyed. Then you don’t need to think about manually cleaning up nullptrs and such.

1 Like