本文介绍了C ++函数返回引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

这里有另一个n00b问题:

Here goes another n00b question:

为什么我不能/不应该将引用返回到函数的局部变量?是因为临时变量在函数完成执行后被自动销毁?

Why is it that I cannot/shouldn't return the referece to a local variable to a function? Is it because the temporary variable is automatically destroyed after the function finishes executing?

const string & wrap(string & s1, const string & s2){
    string temp;
    temp = s2 + s1 + s2;
    return temp;
}

这一个:

const string & wrap2(const string & s1, const string & s2){
    return (s2 + s1 + s2);
}


推荐答案

分配在堆栈上。当一个函数返回到调用者时,堆栈上用于存储变量的空间被回收并且不再可用,并且那里的变量不再存在(它们可以但不能使用它们,并且它们可以是在任何时候被覆盖)。所以是啊,基本上你说的。

Variables declared locally inside functions are allocated on the stack. When a function returns to the caller, the space on the stack where the variable used to reside is reclaimed and no longer usable and the variables that were there no longer exist (well they do but you can't use them, and they can be overwritten at any time). So yeah, basically what you said.

这篇关于C ++函数返回引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:40