Returning a reference can work?

后端 未结 3 1601
天涯浪人
天涯浪人 2021-01-26 05:35

I used to think returning a reference is bad as our returned reference will refer to some garbage value. But this code works (matrix is a class):

co         


        
3条回答
  •  执笔经年
    2021-01-26 06:06

    buf is declared as static, meaning it retains it's value between calls to the function:

    static matrix buf[max_matrix_temp];
    

    i.e. it's not created on the stack as int i = 0; would be (a non-static local variable), so returning a reference to it is perfectly safe.

    This following code is dangerous, because the memory for the variable's value is on the stack, so when the function returns and we move back up the stack to the previous function, all of the memory reservations local to the function cease to exist:

    int * GetAnInt()
    {
      int i = 0;  // create i on the stack
      return &i;  // return a pointer to that memory address
    }
    

    Once we've returned, we have a pointer to a piece of memory on the stack, and with dumb luck it will hold the value we want because it's not been overwritten yet — but the reference is invalid as the memory is now free for use as and when space on the stack is required.

提交回复
热议问题