How does =delete on destructor prevent stack allocation?

The destructor of a variable with automatic storage duration (i.e. a local variable) would need to run when the variable’s lifetime ends. If there is no accessible destructor the compiler refuses to compile the code that allocates such a variable.

Basically the distinction between “stack allocation” (an inaccurate choice of term by the way) and free store allocation is that with local variables constructor/destructor calls always come in pairs, whereas with free store allocation you can construct an object without ever destructing it. Therefore by preventing access to the destructor your code makes it impossible to allocate a local variable of the type (if the constructor runs the destructor must also run, but there is no destructor so the program is rejected).

Leave a Comment