Reputation: 1058
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?
Upvotes: 5
Views: 923
Reputation:
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.
vector<Student> vectorName;
If you don't want the overhead of copying objects when inserting them in the vector, either move them or use emplace_back
:
vectorName.push_back(std::move(student));
vectorName.emplace_back("John", 42);
Upvotes: 2
Reputation: 133577
This mainly depends on where a Student*
references stored. If a Student*
instance has its personal list of students which are not reference any where else then what you are doing generates many dangling pointers.
When destroying a std::vector
the destructor on contained objects is implicitly called, this means that if the objects contained are Student*
then just the space for the pointer is released and you have to manually do what you are doing which is correct IF AND ONLY IF you don't store the same Student* in more than one collection.
So to summarize:
Student*
object must be done if the vector contained the only reference to it.Student*
in a collection will invalidate pointers to it in other collections which will lead to problemsUpvotes: 5
Reputation: 22890
if you allocated item of vectorname
with new Student
, then yes. But you have to remember that after this point any data pointed by a vectorName.at(i)
is destroyed, and should not be accessed somewhere else in the program.
Upvotes: 2