Arr[i] already gets a copy of the element, you don’t need any separate function for that. And Number is just a return value, you don’t need a separate variable for that either.
The function is probably something like:
.h: int32 GetRandomNumber();
You can, but why?
Why use an Out Parameter when you can have a return type? So instead of something like:
int32 Number;
GetRandomNumber(Number);
You can simply do: int32 Number = GetRandomNumber();
or even: SomeOtherFunction(GetRandomNumber());
You can’t do the last two with an out parameter. Out parameters are useful when you need more than one variable to be changed by the function; when there’s only one, use a return type.
what is supposed to be used by C++ version, refference or a copy version?
in blueprint I am using the copy version to avoid propagating any changes to the array itself.
Have you tried getting a ref from the array and changing it in BP? It doesn’t change the array element. I guess in BP it always gets a copy unless it’s the array of pointers.
In cpp, if you don’t do anything specific to get a reference, [i] gets a copy. Unless it’s an array of pointers.
ReturnRandomNumber(int32& Number) //By ref ? and should be (int32 Number) to make it //Getting a copy ?
{
TArray<int32> Arr{};
Number = Arr[FMath::RandRange(0, 99)]; // Number is By ref returning the output?
}
In this case Arr and ByCopy are temporary variables so you don’t want to return the address of invalid memory, you should pass the array you’re working with or access it if it’s available.
You can have it defined in your header or available before calling the function, for this I would recommend returning a pointer so you can check for valid index
TArray<int32> Arr = { 0, 1, 2 };
int32* ArrElem = GetArrByRef(Arr, 0); //Returns a pointer, can be null if index is not valid
int32& ArrElemRef = *ArrElem; //If you want to work with ref variable but be sure ArrElem is not null.
very informative, thank you very much for sharing the expensive information , I will be opening another thread if something goes wrong with my algorithm …