How to deallocate variables on the stack?

前端 未结 6 1824
一向
一向 2021-01-29 14:15

Is there a way to deallocate variables and/or objects created on the stack? I am specifically talking about the stack not the heap.

I do not want to debate whether this

6条回答
  •  天命终不由人
    2021-01-29 15:05

    No, it's not possible to deallocate a stack variable before it goes out of scope in portable C++.

    It would be possible to do something retarded and non-portable with inline assembly like this (example works only with x86, only with Visual Studio):

    int* ptr;
    
    __asm {
        sub esp, sizeof(int)           // allocate variable
        mov [esp + sizeof(int)], esp   // move its address into ptr
    }
    
    *ptr = 4;                          // assign 4 to the variable
    cout << *ptr << endl;              // print variable
    
    __asm {
        add esp, sizeof(int)           // deallocate variable
    }
    

    But don't, there are too many problems to name.

提交回复
热议问题