Aussie AI
Standard Vector Object Resizing
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Standard Vector Object Resizing
The standard vector
class is usually very efficient for basic data types,
but you need to take care if you instantiate it with a class type.
The risk is that you'll have hidden calls to this class type's constructors and destructors,
potentially for every element of the vector
,
under various circumstances.
This slug is a type of “hidden copy constructor call” problem.
If you don't manage the size of the standard C++ vector
class objects in the initialization
or via the “reserve
” method,
there can be a lot of hidden resizing happening behind the scenes
whenever you are adding elements to the vector.
This will at least be doing bitwise copies of the elements of each vector.
But it's even worse if the vector contains complex objects with a defined
copy constructor.
When it's resizing the vector
, it will call the copy constructor for each and every
object that is an element of the vector
because it needs to move them all.
Even for basic data types there can be some cost to copying the data when resizing.
You can take control of this with the “reserve
” function, so that the vector
object
doesn't need to keep resizing itself if you're adding to it.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |