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.
#include <new>
#include <string>
int main() {
typedef std::aligned_storage<sizeof(std::string)> stringbuffer;
stringbuffer buff;
std::string& str =*new(buff)std::string("banana"); //str alive on stack
std::cout << str;
str.~std::string(); // str is destroyed. DO NOT FORGET
std::cout << '\n';
}
This is error prone, so of course, boost has code for this.
int main() {
boost::optional<std::string> str;
str = "banana"; //str is alive on the stack
std::cout << str;
str = boost::none; //str is destroyed. Ok to forget
std::cout << '\n';
}
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.