Is there a way to use the new
keyword to allocate on the stack (ala alloca
) instead of heap (malloc
) ?
I know I could hack up my o
Be careful when using _alloca()
with GCC
GCC has a bug which makes _alloca() incompatible with SJLJ exception handling in C++ (Dwarf2 is reported to work correctly). When an exception is thrown out of the function allocating the memory, the bug causes stack corruption before the destructors get to run. This means that any RAII class working on the allocated object(s) has to run in another function to work properly. The proper way of doing it looks like this:
void AllocateAndDoSomething()
{
Foo* pFoo = reinterpret_cast(_alloca(sizeof(Foo)));
new (pFoo) Foo;
// WARNING: This will not work correctly!
// ScopedDestructor autoDestroy(pFoo);
// pFoo->DoSomething();
// Instead, do like this:
DoSomething(pFoo);
}
void DoSomething(Foo* pFoo)
{
// Here, destruction will take place in a different call frame, where problems
// with _alloca() automatic management do not occur.
ScopedDestructor autoDestroy(pFoo);
pFoo->DoSomething();
}