Question

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?

Was it helpful?

Solution

Nope, it's the impossibles. A class can't allocate function-local memory- that plain doesn't make sense.

However, you can achieve extremely fast heap allocation with a proper custom allocator, like a memory arena- to the point where it's more than fast enough. What you need to remember is that new is the nuclear warhead of memory allocation- it must support any allocation size, and any allocation/deallocation pattern. Something more specific can operate a hell of a lot faster- to the point where it's quite competitive with stack allocated memory. On Visual Studio 2010, I could even get it to execute faster than alloca.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top