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超出此范围 AND //安全,超出此范围 。我不明白为什么那些是安全的,超出了范围。就我研究和理解而言,参数具有局部范围,并且当函数返回要调用的控件时,局部变量超出范围(这使得返回局部变量不安全)。所以,我的问题是为什么它们不会超出范围,为什么它不安全。
答案 0 :(得分:3)
我在下面为您介绍了如何声明变量以及它们在内存中的位置。我希望这有助于解释他们如何安全返回!
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
}
这也是安全的,因为在全局变量池中声明了“static int x”,这意味着它在函数完成后仍然存在。
int main() {
int a = 0;
f(&a);
g(a);
} ///:~
答案 1 :(得分:2)
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
}
在这种情况下,x
是static
,因此它从第一次遇到声明到程序结束时存在。它不会在函数结束时被销毁。
答案 2 :(得分:0)
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也消失了。
但是,静态局部变量可以作为参考安全返回,因为此函数不限制该变量的范围。