指针和引用作为函数中的参数

pointer and reference as arguments in function

本文关键字:参数 函数 引用 指针      更新时间:2023-10-16
int* f(int* x) {
  (*x)++;
  return x; // Safe, x is outside this scope***
}
int& g(int& x) {
  x++; // Same effect as in f()
  return x; // Safe, outside this scope***
}
int& h() {
  int q;
//!  return q;  // Error
  static int x;
  return x; // Safe, x lives outside this scope
}
int main() {
  int a = 0;
  f(&a); 
  g(a);  
} ///:~

对不起,如果我的问题框架是错误的,或者我的基本概念不清楚。这是一个基本级别的怀疑,但我没有通过谷歌搜索得到任何关于我的怀疑。

疑问:上面的代码片段(我在网上找到的)有评论,//安全,x 在此范围之外和//安全,在此范围之外我不明白为什么这些是安全的并且超出了范围。据我研究和理解,参数具有局部范围,当函数返回要调用的控件时,局部变量超出范围(这使得返回局部变量不安全)。所以,我的问题是为什么他们没有超出范围,为什么它不是不安全的。

我在下面为您提供了一些关于变量如何声明以及它们在内存中的位置的评论。我希望这有助于解释他们如何安全返回!

int* f(int* x) {
  (*x)++;
  return x; // Safe, x is outside this scope
}

这是安全的,因为传入了指向 x 的指针(内存地址)。既然是这种情况,这意味着这个函数没有声明原始变量,它来自其范围的外部。

int& g(int& x) {
  x++; // Same effect as in f()
  return x; // Safe, outside this scope
}

这是一个类似的场景,其中 x 的内存地址被传递到函数中,并且没有在函数的作用域中声明

int& h() {
  int q;
//!  return q;  // Error
  static int x;
  return x; // Safe, x lives outside this scope
}

这也是安全的,因为"静态 int x"是在全局变量池中声明的,这意味着它在函数完成后仍然存在。

int main() {
  int a = 0;
  f(&a); 
  g(a);  
} ///:~
int* f(int* x) {
  (*x)++;
  return x; ***// Safe, x is outside this scope***
}

在这种情况下,只有指针本身是函数的本地指针。指针指向的int不是,并且可能在此函数之外创建。您只需将指针返回,该指针继续指向该对象。

int& g(int& x) {
  x++; // Same effect as in f()
  return x; ***// Safe, outside this scope***
}

在本例中,您将返回对 int 对象的引用,该对象也通过引用传入到您的函数。因此,该对象不是本地对象。

int& h() {
  int q;
//!  return q;  // Error
  static int x;
  return x; // Safe, x lives outside this scope
}

在这种情况下,xstatic的,因此它从第一次遇到声明到程序结束就存在。它不会在函数结束时被销毁。

Safe, x is outside this scope

这是针对所有非局部函数的变量。

您的最后一个案例:-

int& h() {
  int q;
//!  return q;  // Error
  static int x;
  return x; // Safe, x lives outside this scope
}

在这里你不能返回 q,因为 q 是函数的本地,所以当这个函数退出时,q 也消失了。

但是,静态局部变量作为引用返回是安全的,因为此函数不会限制该变量的范围。