In C++ you should not be using the C memory management routines. In modern C++ the smart pointers provide you with fine grained deterministic garbage collection.
Though the space allocated via alloca()
is probably deallocated with exceptions (because it is usually done by increasing the size of the current stack frame). This is not part of the standard and thus I don't think you can make any guarantees.
BUT This also means that any appropriate destructors on the object are never going to be called. Which means that if the object does its own memory management this will not be cleaned up (because the destructor is not run to clean it up).
Though alloca()
is probably very fast. I think the extra burden it adds for memory management is (in the general case) not worth it; though if you have a special need for extra speed it may be worth it.
Code the looks like this:
void func()
{
MyType* x = (MyType*)alloca(sizeof(MyType));
passXtoCFunctionThatDoesNotTakeOwnership(x);
}
Should be written like this:
void func()
{
std::unique_ptr<MyType> x = std::make_unique<MyType>();
passXtoCFunctionThatDoesNotTakeOwnership(x.get());
}
If you are using it to hold an array of objects.
void func()
{
MyType* x = (MyType*)alloca(sizeof(MyType) * arraySize);
// STUFF
x[0].stuff();
}
Then it is better to use a std::vector
void func()
{
std::vector<MyType> x;
x.reserve(arraySize); // or resize() if that is appropriate
// STUFF
x[0].stuff();
}
If you are using it for simple objects. Then you should probably just be declaring automatic variables:
void func()
{
MyType* x = (MyType*)alloca(sizeof(MyType));
x->myData = 5;
}
You should just be declaring a variable:
void func()
{
MyType x;
x.myData = 5;
}