Base struct array, pointer with casting

Hi!

There is no troubles with GC in your sample. Your code does exactly following:

 TArray<FItem> bucket; // Creates an array of FItem. FItem have no members inside and have ~zero size (actually non-zero, but without your data)
 
 FNumber n1; // Works as desired
 n1.Value = 3.14f;
 bucket.Add(n1);  // Converts FNumber to FItem and then pass it to an Add method (removes your data completely). 

 FNumber* nPtr = (FNumber*)&bucket[0]; // Uoy assume that there is FNumber in array, but there is only FItem here, so it contains no data.

You can try the common practice for UE:

  1. TArray > YourArray // Creates an array of pointers to your further data
  2. YourArray.Add( MakeShareable( new YourBaseTypeSubclass ) ); // Creates an item and push it into array
  3. TSharedPtr YourItem = StaticCastSharedPtr< YourBaseTypeSubclass >( YourArray[0] ); // Cast type to an actual item
  4. Use YourItem as pointer

Also you can use UObject RTTI facility which gives type safety

TArray ObjectArray;
ObjectArray.Add( NewObject(this)); // this is a container for a newly created object. It is possible to create a new object inside any other UObject instance, but it will be better to create they inside your components or inside a transient package.
UChildObject* ptr = Cast(ObjectArray[0]);

!Important!
To prevent UObject array from being GC’ed you have to turn this array to UPROPERTY()