Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a new equalivant of _malloca

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.

like image 406
rerun Avatar asked Dec 13 '22 23:12

rerun


2 Answers

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...

like image 53
JoeG Avatar answered Dec 15 '22 14:12

JoeG


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;
like image 41
AshleysBrain Avatar answered Dec 15 '22 14:12

AshleysBrain