繁体   English   中英

Scope 堆栈上的变量 c++

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM