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
To allocate on the stack, either declare your object as a local variable by value, or you can actually use alloca to obtain a pointer and then use the in-place new operator:
void *p = alloca(sizeof(Whatever));
new (p) Whatever(constructorArguments);
However, while using alloca and in-place new ensures that the memory is freed on return, you give up automatic destructor calling. If you're just trying to ensure that the memory is freed upon exit from the scope, consider using std::auto_ptr
or some other smart pointer type.