简体   繁体   English

Scope 堆栈上的变量 c++

[英]Scope a variable on stack in c++

Hi there i am new in c++ and my question is related to scope of a variable.嗨,我是 c++ 的新手,我的问题与变量的 scope 有关。 Let me ask the quesion considering the code below让我考虑下面的代码来问这个问题

#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;
}

In the middle function tun() there is a variable named f and when the function return it is poped from the stack as per my knowledge.在中间 function tun()有一个名为f的变量,当 function 返回时,据我所知,它会从堆栈中弹出。 in this case the function return to sun() which is then called in main() and inside main it is giving me correct value of the variable decleard and initialized in function tun() .在这种情况下, function 返回sun() ,然后在 main() 和 main 中调用它,它给了我在 function tun()中 decleard 和初始化的变量的正确值。 Can anybody explain this behaviour to me, i am a bit confused on it.任何人都可以向我解释这种行为,我对此有点困惑。

The variable f is gone, but its value has been stored in the int that the pointer returned by fun points to.变量f消失了,但它的值已经存储在fun返回的指针指向的int中。 The code can be simplified to代码可以简化为

#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;
}

Its not clear what the code is supposed to do other than obfuscation, btw.除了混淆之外,不清楚代码应该做什么,顺便说一句。

tun() returns a pointer that is pointing on memory address of f when tun is no longer on the stack does'nt the memory got destroyed?当tun不再在堆栈上时,tun()返回一个指向f的memory地址的指针,memory没有被破坏吗?

No. There is no pointer to f in your code.不,您的代码中没有指向f的指针。 This line这条线

*(fun()) = f;

assigns the value of f to the int pointed to by the static pointer ptr returned by fun() .f分配给由fun()返回的 static 指针ptr指向的int

It is similar to它类似于

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   !!!

This happens because you assign the value to the pointer created on the heap in fun , the variable f no logner exists发生这种情况是因为您将值分配给在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