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