views:

103

answers:

2

I am a big fan of the _malloca but I can't use it with classes. Is there a stack based dynamic allocation method for classes.

Is this a bad idea, another vestige of c which should ideologically be opposed or just continue to use it for limited purposes.

+4  A: 

You can use _malloca with classes by allocating the memory (with _malloca) then constructing the class using placement new.

void* stackMemory = _malloca(sizeof(MyClass));
if( stackMemory ) {
   MyClass* myClass = new(stackMemory) MyClass(args);
   myClass->~MyClass();
}

Whether you should do this is another matter...

Joe Gauterin
Let's fill in the dots in this answer: this is pointless. The compiler already generates code like this, it never forgets to call the destructor. Even when the code throws an exception.
Hans Passant
What if you want to choose which of several derived classes to instantiate without heap allocation? And of course you need to be careful with calling the destructor - using RAII would be a good idea. But as it currently stands, the code in the answer never fails to call the destructor, even when an exception is thrown.
Joe Gauterin
+3  A: 

You should probably avoid _malloca where possible, because you can cause a stack overflow if you allocate too much memory - especially a problem if you're allocating a variable amount of memory.

Joe's code will work but note the destructor is never called automatically in the case an exception is thrown, or if the function returns early, etc. so it's still risky. Best to only keep plain old data in any memory allocated by _malloca.

The best way to put C++ objects on the stack is the normal way :)

MyClass my_stack_class;
AshleysBrain