[英]Scope a variable on stack in c++
嗨,我是 c++ 的新手,我的問題與變量的 scope 有關。 讓我考慮下面的代碼來問這個問題
#include <iostream>
static int* fun(){
static int *ptr = new int(4);
return ptr;
}
static int * tun() noexcept{
int f = 111;
*(fun()) = f;
return fun();
}
static int *sun(){
return tun();
}
int main() {
std::cout << (*sun()) << std::endl;
}
在中間 function tun()
有一個名為f
的變量,當 function 返回時,據我所知,它會從堆棧中彈出。 在這種情況下, function 返回sun()
,然后在 main() 和 main 中調用它,它給了我在 function tun()
中 decleard 和初始化的變量的正確值。 任何人都可以向我解釋這種行為,我對此有點困惑。
變量f
消失了,但它的值已經存儲在fun
返回的指針指向的int
中。 代碼可以簡化為
#include <iostream>
int * tun() {
static int* ptr = new int;
int f = 111;
*ptr = f; // copy value of f
return ptr;
} // f is gone now, but who cares?
int main() {
std::cout << (*tun()) << std::endl;
}
除了混淆之外,不清楚代碼應該做什么,順便說一句。
當tun不再在堆棧上時,tun()返回一個指向f的memory地址的指針,memory沒有被破壞嗎?
不,您的代碼中沒有指向f
的指針。 這條線
*(fun()) = f;
將f
的值分配給由fun()
返回的 static 指針ptr
指向的int
。
它類似於
int x = 0;
int* ptr = new int;
*ptr = x; // assigns 0 to the int pointed to by ptr
std::cout << *ptr; // prints 0
assert( ptr != &x); // adress of x ist not ptr !!!
發生這種情況是因為您將值分配給在fun
中創建的堆上的指針,變量f
no logner 存在
#include <iostream>
static int* fun(){
static int *ptr = new int(4); // 4 stored inside pointer
return ptr;
}// ptr still exists because it's heap allocated
static int * tun() noexcept{
int f = 111; //f holds value 111
*(fun()) = f; // ptr now stores the value 111
return fun();
} // f gets destroyed, ptr still holds 111
static int *sun(){
return tun();
}
int main() {
std::cout << (*sun()) << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.