Return Type

Returning Pointer vs. Reference?

(2023-08-31): Had this thought recently: what is the difference between returning a pointer, vs. returning a reference? It seems that both are kind of similar, where you are extending the lifetime of the object beyond the stack.

Found my answer through https://stackoverflow.com/questions/7813728/pointer-vs-reference-return-types Also see https://stackoverflow.com/questions/752658/is-the-practice-of-returning-a-c-reference-variable-evil

The difference: References CANNOT be null. You can think of references as “pointers to existing objects”. You shouldn’t really create a new object from inside the function, and return a reference to it, because the variable will get deleted as soon as we exit the function.

  • Although you can extend the variable’s lifespan by a bit, see rvalue, not by much though

In practice, sometimes I return references to unique_ptr.

https://stackoverflow.com/questions/752658/is-the-practice-of-returning-a-c-reference-variable-evil

int& getInt() {
    int i;
    return i;  // DON'T DO THIS.
}

Erroneous usage

int& getInt()
{
    int x = 4;
    return x;
}

This is obviously error

int& x = getInt(); // will refer to garbage

Other Scenario

what happens here? is x copied?

int& getInt()
{
    return x;
}
int x = getInt(); 
  • int x = getInt(); is executed, it initializes x with the value referred to by the reference returned by getInt(). This operation does not involve copying the reference itself but rather copying the value it refers to into x.

Basically, don’t get confused, there is Return Value Optimization.

Usage with static variables

int& getInt()
{
   static int x = 4;
   return x;
}