3
votes

What is the difference looking from memory menagement site between using one vector class member for all temp vectors used in functions:

class A
{
   private:
   vector<Type> m_vector;
}

void fnc()
{
   m_vector.clear();
   m_vector.push_back();
   //further operations on vector
}

and creating temp vectors inside of functions:

void fnc()
{
    vector<Type> vector;
    //further operations on vector
}

I suppose first option results in less memory fragmentation, cause we are doing one allocation and using this area, and in second case we are allocating memory for vectors in different functions which results in memory fragmentation.

What are the pros and cons of this vector usages? Which one should I use when I have class which needs many vectors in its functions? And which one is better looking from memory menagement site?

3

3 Answers

9
votes

Your solution might be better from memory management point of view because of fragmentation and fewer allocations/deallocations but :

  • You become less thread safe in a multithreaded environment - you might need to implement some synchronization in each method around the use of the vector
  • You need to remember to clear the vector's contents in each method
6
votes

Simple rule:
If you want the vector to exist till the lifetime of your class object make it a class member else don't.

In short, You should use it as member if its lifetime is tied to the lifetime of the object.
If not, all you need is local vectors.
Whether the first or second approach is more appropriate for your usage is Micro-Optimization avoid them unless your usage is expected to be heavy enough to be worried avoid it.

1
votes

Don't make a member vector just for the purpose of re-usage. Whether something is a member or not should be based on the logic of the class.