返回對本地或臨時變量的引用看下面的代碼。我知道它不會返回局部變量的地址,但為什么它仍然有效并將imain()中的變量賦值為'6'?如果從堆棧內(nèi)存中刪除變量,它如何僅返回值?#include <iostream>int& foo(){
int i = 6;
std::cout << &i << std::endl; //Prints the address of i before return
return i;}int main(){
int i = foo();
std::cout << i << std::endl; //Prints the value
std::cout << &i << std::endl; //Prints the address of i after return}
3 回答

HUX布斯
TA貢獻1876條經(jīng)驗 獲得超6個贊
你真是幸運。從函數(shù)返回不會立即擦除剛剛退出的堆棧幀。
順便說一下,你是怎么證實你有6回來的?表達式std::cout << &i ...
打印的是地址i
,而不是其值。

嚕嚕噠
TA貢獻1784條經(jīng)驗 獲得超7個贊
地址i
永遠不會改變main()
,但其中包含的值將會改變。您正在引用局部變量并在該引用超出范圍之后使用它。(不精確的語言警告)值6
在堆棧上。由于在放入堆棧后沒有對堆棧執(zhí)行任何操作,因此6
對它的引用仍將包含相同的值。所以,正如其他人所說,你很幸運。
要查看有多幸運,請在調(diào)用后嘗試運行使用堆棧的代碼foo()
:
#include <iostream>#include <ctime>#include <numeric>int& foo(){ int i = 6; std::cout << &i << " = " << i << std::endl; //Prints the address of i before return return i;}long post_foo(int f){ srand((unsigned)time(0)); long vals[10] = {0}; size_t num_vals = sizeof(vals)/sizeof(vals[0]); for( size_t i = 0; i < num_vals; ++i ) { int r = (rand()%2)+1; vals[i] = (i+f)*r; } long accum = std::accumulate(vals, &vals[num_vals], 0); return accum * 2;}int main(){ int &i = foo();// std::cout << "post_foo() = " << post_foo(i) << std::endl; std::cout << &i << " = " << i << std::endl; }
當(dāng)我通過post_foo()
注釋掉的調(diào)用運行它時,6
仍然在堆棧上,輸出是:
002CF6C8 = 6002CF6C8 = 6
...但是當(dāng)我沒有評論這個電話post_foo()
并再次播放時,它6
早已不復(fù)存在:
001FFD38 = 6post_foo() = 310001FFD38 = 258923464
- 3 回答
- 0 關(guān)注
- 539 瀏覽
添加回答
舉報
0/150
提交
取消