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 would be useful or good practise, I just need to know if it’s possible.
I know it automatically deallocates when it goes out of scope. I want to deallocate it BEFORE it goes out of scope.
I am using C++.
You cannot prematurely end the lifetime of an “automatic” object, but you can end the lifetime of a dynamic object at any time. A dynamic object can be created on the stack just like an automatic variable, but it’s a hair trickier.
This is error prone, so of course, boost has code for this.
Both of these avoid the potential UB of FredOverflow’s answer, since if an exception is thrown while the object is not alive, the destructor is not automatically called on the dead object.
Azza notes that this does not deallocate the space, it merely destructs. It is impossible to deallocate the space early.