code code - 1 month ago 22
C++ Question

Stack or Heap in inderect heap allocation

is funcVar on stack or heap in scenario 1?

I'm asking because I suspect that it is, and hence this may be a good way to do things to minimize memory leaks. that is to say, it may be better to give things auto allocation locations and then place code at higher levels on the heap which would put things at lower levels on heap indirectly as in scenario 1.

In scenario 2, delete may never be called. By using code as in scenario 1, I hope to minimize (not eliminate) issues as in scenario 2.

Scenario 1

class Test{
int memVar = 1;

void func(){
int funcVar = 2;
SomeClass::someFuncThatCouldCrash();
}
};

Test* t = new Test();


Scenario 2

class Test{
int memVar = 1;

void func(){
int* funcVar = new int(2);
SomeClass::someFuncThatCouldCrash();
delete funcVar; //May not free due to crash in line above;
}
};

Test t; //or Test* t = new Test()

Answer

In scenario 1 funcVar (assuming it is int funcVar = 2) is on the stack when func() is called and in scenario 2 it is on the heap. You are correct, if someFuncThatCouldCrash threw an exception it would never be deleted.

Also, in scenario 2 you delete funcVar and then return it.. that's no good. Also in that case your returning a pointer when the return type is a regular int.

In C++11 you don't ever want to handle raw new and delete. Basically, most everything should be a variable on the stack. If you need heap allocations, use something like a vector which is a local variable on the stack that manages heap allocations internally. That way, when the vector leaves scope it cleans up itself without ever having to call delete. This is known as RAII (resource allocation is initialization) if you want to look it up further.

In the case that you do need a pointer to an object (such as holding a polymorphic object via base-class pointer, or creating instances of large classes in general) then you would want a std::unique_ptr to essentially create that local variable which is responsible for calling delete on the object you created. Under rarer circumstances you also may need a std::shared_ptr but you can look up what that does and why you'd need it if you want.