下面是一段返回临时变量引用的代码:

#include "stdafx.h"
#include "conio.h"
#include "windows.h"

int &same()
{
  int a = 2;
  return a;
}

int main()
{
  int &b = same();

  for (;;)
  {
    printf("b value is : %d\n", b);
    Sleep(200);
  }
  
  return 0;
}

执行结果打印如下:

不能返回临时变量的引用

b 的值被改变了。

 

相关文章: