While creating and using std::vector with user defined classes we needs some special care otherwise it can hamper the performance of our application.

Let’s learn by example,

Suppose we have an Item Class,

And we want to create a vector of 10000 Item objects.
So, let’s create a factory class for it,

Now let’s use this factory to create objects,

Above code seems fine, we created 10000 objects of class Item. But while creating these 10000 object we wasted  20000 objects, that’s double of what we actually needed.

Output on g++ 4.8.1,

Output on g++ 4.8.1

Culprit in this case is the getItemObjects function from ItemFactory class i.e.

  • Inside the for loop we created 10000 objects, so constructor is called 10000 times.
  • Then after creating every object we inserted the newly created object in vector 10000 times, therefore copy constructor is called 10000 times and destructor of old 10000 Item object is called.
  • In last line of function, we returned the vector and all its content was copied to vecOfItems vector, so again 10000 times copy constructor is called and destructor of old 10000 Item object is called.

This shows how we wasted 20000 objects.

Now with a small change we can reduce the wasted object count to 10000 from 20000 i.e.

Instead of these 2 lines,


With this, instead of copying 10000 objects, all objects will be moved to new vector. So, now output will be,

Output on g++ 4.8.1


So, with this instead of 20000 we wasted only 10000 objects.

But still we are wasting 10000 objects. How to fix that?

We can do this by 2 ways,

1.) Instead of returning the whole new vector from factory function, just passing the new vector as a reference to factory function i.e.

It’s output will be,



So, now we are just wasting 1 object.

2.) Just use the vector’s assign function to create the 10000 copies of 1 object i.e.

It’s output will be,


So, with this too we are just wasting 1 object.

Similarly, we should also avoid passing vector to functions by value whenever possible to avoid this kind of memory wastage

Complete code is as follows,

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.