指针和引用作为函数中的参数
pointer and reference as arguments in function
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
}
在这种情况下,x
是static
的,因此它从第一次遇到声明到程序结束就存在。它不会在函数结束时被销毁。
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 也消失了。
但是,静态局部变量作为引用返回是安全的,因为此函数不会限制该变量的范围。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类