I'm a bit confused as to how destructors are called on objects constructed through vector, but only once when I create object using pointer.
#include <iostream>
#include <vector>
#include <string>
class Student
{
std::string first;
std::string last;
int age;
public:
Student();
Student(std::string f, std::string l, int a) : first(f), last(l), age(a)
{
};
~Student()
{
cout << "Destructor\n";
}
};
int main()
{
std::vector<Student> Univ;
Univ.push_back(Student("fn1", "ln1", 1));
Univ.push_back(Student("fn2", "ln2", 2));
Univ.push_back(Student("fn3", "ln3", 3));
return 0;
}
When I push back one time, I get 2 calls to destructor. 2 push backs, I get 5 calls to destructor. 3 push backs, I get 9 calls to destructor.
Normally if I do something like this,
Student * Univ = new Student("fn1", "ln1", 1);
delete Univ;
I get just one call to destructor.
Why is this?