16

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 own but I'd rather not.

Yu Hao
  • 111,229
  • 40
  • 211
  • 267

4 Answers4

23

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<T> or some other smart pointer type.

Jeffrey Hantin
  • 33,679
  • 7
  • 71
  • 92
12

Jeffrey Hantin is quite correct that you can use placement new to create it on the stack with alloca. But, seriously, why?! Instead, just do:

class C { /* ... */ };

void func() {
    C var;
    C *ptr = &var;

    // do whatever with ptr
}

You now have a pointer to an object allocated on the stack. And, it'll properly be destroyed when your function exists.

derobert
  • 45,779
  • 11
  • 86
  • 120
  • 2
    Your example is exactly what I meant by declaring it as a local variable by value. – Jeffrey Hantin Jan 23 '09 at 22:41
  • note: the class must have an empty constructor defined in cpp, if you already have a non-empty constructor defined. – Kevin Jul 11 '14 at 21:00
  • use case I've got - say `C` has a `virtual` method overridden in subclasses `C1` and `C2`. Then I may want to do `C * ptr = criteria ? new (alloca(sizeof(C1))) C1(...) : new (alloca(sizeof(C2))) C2(...);` – rampion Sep 26 '16 at 19:59
6

You could do:

Whatever* aWhatever = new ( alloca(sizeof(Whatever)) ) Whatever;

You could uses a RAII class to do the destruction I suppose (EDIT: Also see this other answer for more information on potential problems with this approach):

template <class TYPE>
class RAII
    {
    public:
        explicit RAII( TYPE* p ) : ptr(p) {}
        ~RAII() { ptr->~TYPE(); }
        TYPE& operator*() const { return *ptr; }
    private:
        TYPE* ptr;
    }

void example()
    {
    RAII<Whatever> ptr = new ( alloca(sizeof(Whatever)) ) Whatever;
    }

You could use a macro to hide the alloca.

Regards DaveF

Community
  • 1
  • 1
David Allan Finch
  • 1,288
  • 6
  • 18
2

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<Foo*>(_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();
}
Carl Seleborg
  • 12,771
  • 11
  • 51
  • 70