std::vector
In Custom vector, part 3, we tried most of the things that we can do to optimize our vector, but still we end up using unnecessary memory. Thus, instead of trying to create a perfect implementation, we can use a std::vector
implementation that will provide is the most optimised way to create a vector.
Here's a brief explanation along with an example:
Let's break down the key points:
We define a
Person
class with a name and age.The class includes a regular constructor, a copy constructor, and a move constructor. Each constructor logs when it's called.
In the
main
function, we create a vector ofPerson
objects.We use
emplace_back()
to constructPerson
objects directly in the vector, which is more efficient thanpush_back()
for non-trivial objects.We create a copy of the vector, which triggers the copy constructor for each
Person
object.We demonstrate that the original and copied vectors are independent by adding a new person to the original vector.
When you run this program, you'll see logs for each constructor call, allowing you to track when objects are being created, copied, or moved. This is particularly useful for understanding the behavior of vectors and optimizing performance.
Key observations from the output:
When adding elements with
emplace_back()
, only the regular constructor is called.When creating a copy of the vector, the copy constructor is called for each element.
The original and copied vectors are independent; changes to one don't affect the other.
This example showcases how vectors work with custom classes and highlights the importance of properly implementing constructors, especially when dealing with resource management in more complex classes.
Last updated