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.
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...
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With