Possible Duplicate:
Proper stack and heap usage in C++?
Heap vs Stack allocation
I’m trying to understand why a Library I ported from Java to C++ (long and arduous editing work after using a converter) doesn’t free up memory and just explodes the Virtual Memory till crash.
Obviously this has to do with Java having a GC and C++ not – and the algorithms are pretty straight converted to C++.
So here’s my question. Where and how do I delete allocated memory (Free it)? When I have:
Matrix *mat = new Matrix(args);
I obviously need to end the scope with a delete mat;. Can I avoid this?
Would using Matrix mat(args); be better? in terms of Memory Allocation and freeing?
Or using Matrix mat = Matrix(args)?
In most cases, if you coded things properly, you don’t have to explicitly free or de-allocate any memory. Either use automatic allocation, or smart pointers. Otherwise, the answer to where is rather unsatisfying: wherever you need to, depending on your program. The answero to how is simpler: with
delete(ordelete[]for dynamically allocated arrays).Yes, if you use automatic allocation:
As a general rule, you should only use dynamically allocated objects if you really need to. If you don’t know if you really need to, then you probably don’t.
This performs a copy initialization, and in this context provides no advantages over
Matrix mat(args);. The RHS of the expression is a temporaryMatrixobject, which gets used to copy construct the LHSmat.Here is a recent related post.