当传递a = 4时,给定的函数返回:
int* temp1(int a)
{
int b = a*2;
return &b;
}
int* temp2(int a)
{
int b = a*2;
int *p = &b;
return p;
}
int main()
{
cout << *temp1(4); // error
cout << *temp2(4); // output = 8
}
为什么以上两个功能具有不同的行为?而以下具有相同的输出?
int a = 3;
cout << *(&a); // 3
和
int a= 3;
int *p = &a;
cout << *p; // 3
两个功能的行为是相同的。两者均返回指向局部变量的指针。函数返回时,指向对象的生存期都结束。因此,如果程序取消引用返回的指针之一,则该程序的行为是不确定的。