brentf
brentf

Reputation: 411

Effective use of stack vs. heap memory allocation in C++

I am developing a large, complex model (mostly simple math, primarily algebra, but lots of calculations). I did my initial bid assuming I'd have to do everything once, but now the scope has expanded such that I need to run the entire model multiple times (on the same set of underlying assumptions but with a different dataset).

Based on my initial needs, I created a bunch of classes, then created dynamic instances of those classes in my main function, passing them by reference to each function as I went. That way, at the end of the main function, I can do all the necessary reporting / output once all of the functions have run. My question is about how to now modify my main function to allow for multiple iterations. A few sample bits of code below, followed by my question(s):

 // Sample class declaration (in main)
 vector<PropLevelFinancials> PLF;

// Sample function call (functions in other header files)
ProcessPropFinancials(vector<PropLevelFinancials>& PLF);

// Reporting at the end of main (functions in other header files)
OutputSummaryReport(vector<PropLevelFinancials>& PLF, other objects);

// What I need to do next
// Clear/Delete PLF and other objects, iterate through model again

I am quite happy with the speed and result of my current program, so don't need a whole lot of input on that front (although always welcome suggestions).

How should I implement the ability to cycle through multiple datasets (I obviously know how to do the loop, my question is about memory management)? Speed is critical. I want to essentially delete the existing instance of the class object I have created (PLF), and then run everything again on a new instance of the object(s). Is this the type of situation where I should use "new" and "delete" to manage the iterations? Would that change my function calls as outlined above? If I wanted to avoid using new and delete (stay on the stack), what are my options?

Upvotes: 2

Views: 459

Answers (1)

Puppy
Puppy

Reputation: 146900

No. Do not, ever, use new and delete without a highly exceptional cause.

std::vector<T> offers a clear() member you can use. I suggest you implement a similar one for your own classes if that is what you need. Or you can simply do PLF = std::vector<T>();, which would work a bit better for your own UDTs without modification, assuming that you wrote them according to the most basic C++ guidelines.

Upvotes: 4

Related Questions