Skip to content

Instantly share code, notes, and snippets.

@Seathus
Forked from tenpn/InvisibleCopies.cpp
Last active September 11, 2023 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Seathus/66f816205caf378f17a57be336a44560 to your computer and use it in GitHub Desktop.
Save Seathus/66f816205caf378f17a57be336a44560 to your computer and use it in GitHub Desktop.
struct FWidget
{
FWidget() : Name() {}
FWidget(FString Name) : Name(Name) {}
FWidget(const FWidget& Other) : Name(Other.Name) {}
void ProcessIntensity(float Intensity) { /** **/ }
FString Name;
}
//we want pass by reference of an existing list not a new copy of the list being passed in so we take an address location for WidgetsToProcess
//the list now contains pointers instead
void ProcessWidgets(const TArray<FWidget*>& WidgetsToProcess, float Intensity)
{
//change the auto to FWidget*, we want to avoid a copy being generated in the for loop as a copy can happen during this iterated process
for(FWidget* Widget : WidgetsToProcess)
{
//widget is now a pointer to . becomes ->
Widget->ProcessIntensity(Intensity);
}
}
//to avoid a copy, we return an address of the newly created widgets array
//the array also needs to be an array of pointers so we're iterating through, we prevent copies.
TArray<FWidget*>& CollectWidgets()
{
TArray<FWidget*> Widgets;
// collect
return Widgets;
}
// returns default Widget if can't be found
//we want pass by reference of an existing list not a new copy of the list being passed in so we take an address location for WidgetsToProcess
//the list now contains pointers instead
FWidget* FindWidget(const TArray<FWidget*>& WidgetsToSearch, FString Name)
{
//change the auto to FWidget*, we want to avoid a copy being generated in the for loop as a copy can happen during this iterated process
for(const FWidget* Widget : WidgetsToSearch)
{
//widget is now a pointer to . becomes ->
if (Widget->Name == Name)
{
return Widget;
}
}
//we're returning a pointer and want to keep the reference to the newly created object on the heap (FWidget) so we return new
return new FWidget();
}
void Main()
{
//widgets should contain a list of pointers, pointers we can rely on later on.
const TArray<FWidget*> Widgets = CollectWidgets();
ProcessWidgets(Widgets, 99.9f);
//return a pointer to found widget
const FWidget* Found = FindWidget(Widgets, TEXT("Find me"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment