At what exact moment is a local variable allocated storage?

后端 未结 5 792
执笔经年
执笔经年 2020-12-10 15:19

Suppose we have the following:

void print()
{
     int a;  // declaration
     a = 9;
     cout << a << endl;
}

int main ()
{
     print();
}
         


        
5条回答
  •  遥遥无期
    2020-12-10 15:43

    As for construction of objects:

    Construction happen at the point of declaration, and the destructor is called when the object goes out of scope.

    But construction of objects and when memory is allocated do not need to coincide.

    Just as destruction of objects and when memory is deallocated do not need to coincide.

    As for when the memory on the stack is actually allocated:

    I don't know, but you could check via the following code:

    void f()
    {
      int y;
      y = 0;//breakpoint here
    
      int x[1000000];
    }
    

    By running this code you can see where the exception happens, for me on Visual Studio 2008 it happens on entry of the function. It never reaches the breakpoint.

提交回复
热议问题