返回对局部变量的引用 [英] returning references to local variable
问题描述
可能重复:
返回本地或临时变量的地址
可以在其范围之外访问局部变量的内存吗?
即使知道下面剪辑的结果会发生什么,这将有助于理解它的发生。以下四个问题。
给定:
foo()
{
int i = 1;
return i;
}
并且知道在下面引用 被解引用到分配给intVal和本地i 的结尾的temp中。foo()
int intVal = foo();
第一个问题 - 在下面,表达式的右侧与上述相同,因此这种情况下,编译器看到左手边,并基于上下文,知道不取消引用返回的引用,而是创建一个新的引用用它初始化?
第二个问题 - 这只会使局部i 在intRef在范围内时出现?
int& intRef = foo();
第三个问题 - intPtr / strong>。所以,是编译器使用分配的上下文,并决定不取消引用以获取引用的地址之前获取值(而不是说包含取消引用的值的临时表的地址)?
第四个问题 - 本地化是否在 intPtr 范围内?
int * intPtr =& foo();
解决方案不,这些都不会延长局部变量。 C ++中的 不会有此效果。 C ++中的局部对象直到它们被声明的范围的末尾,故事结尾。
唯一的规则,乍一看,似乎遵循不同的规则是这样的:
int foo(){
return 42;
}
int main(){
const int& i = foo();
//这里,`i`是从`foo`返回的临时变量的引用,它的生命周期已被扩展
}
也就是说, const 引用可以延长分配给它的临时的生命周期。
但是这要求函数返回一个值而不是一个引用,并且被调用者将返回值绑定到一个const引用,这两个都不在你的代码中。 p>
Possible Duplicate:
Returning the address of local or temporary variable
Can a local variable’s memory be accessed outside its scope?Even knowing what happens as a result of the following snips it would be helpful to understand how it is happening. Four questions follow.
Given:
int& foo() { int i = 1; return i; }
And knowing that in the following a reference to the local named i is de-referenced into a temp that is assigned to intVal and local i disappears at the end of foo()
int intVal = foo();
First question - in the following, the right hand side of the expression is the same as above so is this a case where the compiler sees the left hand side and, based on context, knows not to de-reference the returned reference, and instead to create a new reference is initialized with it?
Second question - and this alone makes the local i stick around while intRef is in scope?
int& intRef = foo();
Third question - bellow intPtr gets address of local i. So, is the compiler using the context of the assignment and deciding to not de-reference to get a value before taking the address of the reference (rather than say taking the address of a temp containing the de-referenced value)?
Fourth question - does local i stick around while intPtr is in scope?
int* intPtr = &foo();
解决方案Nope, none of those will extend the lifetime of the local variable. Nothing in C++ will have that effect. Local objects in C++ live until the end of the scope in which they are declared, end of story.
The only rule which, at first glance, seems to follow different rules is this:
int foo() { return 42; } int main() { const int& i = foo(); // here, `i` is a reference to the temporary that was returned from `foo`, and whose lifetime has been extended }
That is, a const reference can extend the lifetime of a temporary being assigned to it.
But that requires the function to return a value, not a reference, and the callee to bind the return value to a const reference, neither of which are done in your code.
这篇关于返回对局部变量的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!