How does automatic memory allocation actually work in C++?

后端 未结 5 1330

In C++, assuming no optimization, do the following two programs end up with the same memory allocation machine code?

int main()
{     
    int i;
    int *p;         


        
5条回答
  •  天命终不由人
    2020-12-09 00:19

    No, without optimization ...

    int main() 
    {      
        int i; 
        int *p; 
    }
    

    does almost nothing - just a couple of instructions to adjust the stack pointer, but

    int main() 
    { 
        int *p = new int; 
        delete p; 
    }
    

    allocates a block of memory on heap and then frees it, that's a whole lot of work (I'm serious here - heap allocation is not a trivial operation).

提交回复
热议问题