For testing purposes, I was trying to create my own vector class, and I couldn't figure out how std::vector
size reduction works.
class A
{
A()
{ std::cout << "A constructed") << std::endl; }
~A()
{ std::cout << "A destroyed") << std::endl; }
}
main()
{
std::vector<A> vec(3, A());
vec.resize(2);
std::cout << "vector resized" << std::endl;
}
Output is
A constructed (1)
A constructed (2)
A constructed (3)
A destroyed (1)
Vector resized
A destroyed (2)
A destroyed (3)
When vec.resize(2)
is called, the third element is destroyed, but the vector's capacity is still 3. Then when vec
is destroyed, all of its elements including the one already destroyed should be destroyed. How does std::vector
know that he has already destroyed that element? How can I implement that in my vector class?