【问题标题】:Difference between returning address and returning a pointer in c++ function [duplicate]在c ++函数中返回地址和返回指针之间的区别[重复]
【发布时间】:2020-04-16 15:49:41
【问题描述】:

当传递 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

【问题讨论】:

标签: c++ pointers function-pointers


【解决方案1】:

两个函数的行为是相同的。两者都返回一个指向局部变量的指针。当函数返回时,指向对象的生命周期都结束。因此,如果您的程序取消引用返回的指针中的任何一个,则程序的行为是未定义的。

【讨论】:

  • 最后一部分说的很好。如果您实际尝试使用返回的指针,则只有 UB。尽管那时您会质疑如果不允许使用该指针,函数返回指针的意义何在。
猜你喜欢
  • 2016-03-16
  • 2020-12-12
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 2017-07-18
  • 2017-03-27
  • 2012-12-22
  • 1970-01-01
相关资源
最近更新 更多