rerun
rerun

Reputation: 25505

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.

Upvotes: 4

Views: 2415

Answers (2)

AshleysBrain
AshleysBrain

Reputation: 22591

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;

Upvotes: 5

JoeG
JoeG

Reputation: 13192

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

Upvotes: 8

Related Questions