jeudi 9 avril 2020

How do I know when it's time to make a temporary variable a member variable instead?

Whenever I'm working on scientific projects in C++, sooner or later I find myself calling methods that need to allocate big temporary objects in memory (e.g. vectors/matrices) needed to compute the final result.

My question is then: when should I consider making these temporaries member variables of the class instead? My reasoning is that if they are members already, then there is no need to allocate new memory every time a method is called that needs to access them to store temporary data. At the same time though, the more memory I allocate for "big" member variables, the harder it might be to find suitable chunks of memory for performing other tasks.

I know that in general member variables should represent some sort of property associated to a class, but memory-wise it seems advantageous to create more member variables at first glance.

Of course this is assuming that pointers or references are already being used where the address of a variable can be used.

I wasn't able to find any clear answer. I hope this is clear, please ask for any clarification if needed.

Aucun commentaire:

Enregistrer un commentaire