Takes arguments by ref but returns by val?

What I always could not understand well are the memory manipulation in C++.
Ok, I perfectly understand why you pass arguments by reference. When control is passed to function, the small reference has to be allocated on stack and assigned to some memory location. Is this correct?

But then, why are we allowed to return things by value? For example, in the GetValidWords, we return an array of FString. What happens than? This array is copied onto stack? Or? Shouldn’t we create FString with the ‘new’ keyword and return a reference or pointer to it?

Sorry if this is complete non-sense, C++ is really difficult in this sense just because there is no clear guidance or at least I have not found one. I would be happy if you could resolve this for me. Thanks!

References are implemented as pointers, so yes.

Return value optimisation (RVO) is something that has existed in compilers for decades. In a nutshell when returning a local variable from a function the compiler will pass in the location of the return value into the function.

FString DoSomething()
{
    FString Something = ...;
    //do something
    return Something;
}

void Foo()
{
    FString SomeString = DoSomething();
}

So with (Named)RVO SomeString and Something are the same object.

https://stlab.cc/tips/stop-using-out-arguments.html

Privacy & Terms