0

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?

void-pointer
  • 14,247
  • 11
  • 43
  • 61
  • Is there a reason that you must use the stack to allocate instead of heap? – TheSteve Jul 31 '12 at 00:23
  • 1
    @void-pointer grab a chunk of memory from the heap and use it as your own efficient stack. – R. Martinho Fernandes Jul 31 '12 at 00:24
  • @void-pointer: You might be surprised at how fast the heap is. Some workarounds are to (1) have a static function that calculates how much space must be reserved by the calling function, and (2) use a macro "constructor". But really, just use the heap. – Mooing Duck Jul 31 '12 at 00:25
  • The reason I actually wanted to do this is to determine exactly how heap allocation compares to alloca() within my application. – void-pointer Jul 31 '12 at 00:26
  • @void-pointer: in that case, also test a custom stack allocator. – Mooing Duck Jul 31 '12 at 00:26

1 Answers1

5

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.

Puppy
  • 144,682
  • 38
  • 256
  • 465