I have a homework problem, in which I have a class Student, and a vector of pointers to Student objects, which is a member field in the Student class:
vector<Student*> vectorName;
In order to do correct(?) memory management, I declared the destructor in the Student class like this
Student::~Student() {
for(int i=0; i<vectorName.size(); i++){
delete vectorName.at(i);
}
}
Does this really free the memory correctly from the heap, or is there a better way?
If the vector owns the students (that is, it is responsible for deleting them), don’t use pointers at all (unless you need polymorphism, but you didn’t state that in the question so I assume you don’t). If you do this, you don’t need to explicitly define the dtor, the copy ctor and the copy assignment operator anymore; see the Rule of Zero.
If you don’t want the overhead of copying objects when inserting them in the vector, either move them or use
emplace_back: