Download

Should I return reference or not for local TArray?

Hi! I am struggling with this dilemma. I have



TArray<> somefunction()
{
  TArray<> largeArray;

  return largeArray;
}

I guess, here I return the copy of largeArray, and it is likely not good for performance?

So, my idea was to:


TArray<> somefunction()
{
  TArray<> largeArray;

  return &largeArray;
}

But, then I googled, that local reference gets destroyed, and I should never do that.

What is actually the proper way to code it here? I want that local variable to be created inside function scope, so passing it back as copy is the only way then?

If you want it local then you must return a copy.

Got it, thanks! Seems like I need to re-think function scope, to avoid local variables in such cases.

Yes, you mustn’t return a reference to a local variable.
However, you have the option to return a copy, or create and return a pointer.



TArray<> *somefunction() {
   TArray<> *var = new TArray<....>
   ...
   return var;
}


If your TArray is large, this may save copying overhead.

A third option is to pass in an empty TArray by reference, and just populate it in the function.

You could try passing in a TArray by reference and then filling it inside the function, i.e.


void somefunction(TArray<>& largeArray)
{
  // change 'largeArray' here
}

However, if you are returning the TArray<> into the initialization/construction of a TArray<> variable, i.e.


TArray<> myNewArray = someFunction();

There is the possibility that the compiler may optimize it via Return Value Optimization, however I think it best to code defensively and presume that the optimization won’t occur. Through that lens, returning by parameter argument would be a nice balance (although that isn’t what you asked about).