Several compilers support extensions to C++ whereby one can dynamically allocate memory on the stack. For instance, g++
supports alloca()
as well as VLAs. All of these extensions come with the caveat that the dynamically-allocated memory is "deallocated" at the end of the scope of the calling function. (Edit: To clarify, I use quotes around 'deallocated' because what's actually happening is that the compiler is decrementing/incrementing the stack pointer, hence why alloca()
requires compiler support.) This means that memory allocated using alloca()
within the constructor of a class is deallocated as soon as the constructor returns.
This restriction becomes to difficult to deal with in classes where the constructor goes through some nontrivial steps to determine how much memory to allocate. The user of the class must allocate the memory in the function from which the class is constructed, exposing some internals that arguably should not be exposed. Moreover, putting workarounds in my code to be able to use alloca()
or VLAs is generally inconvenient.
Can you think of some way to circumvent this restriction so that I can use alloca()
, VLAs, or some other language extension, so that the memory can be allocated within the class and have class scope?