Reputation: 810
This is an assignment from my course which I am having trouble to understand the reasoning behind.
We have a class Person which has no pointers and a class Car as follows:
class Car{
public:
//stuff
private:
Person* owner;
};
And then a function which is as following:
void f() {
vector<Car> v;
// do stuff with the vector
}
When the function is finished, there is a memory leak, to fix it the course material recommends to go through each Car in the vector and delete the owner pointer at the end of the function f(). Is it not sufficient to simply write a destructor for Car which deletes its owner to prevent the memory leak?
By simply adding this in the Car class:
~Car() {
delete owner;
}
Upvotes: 3
Views: 100
Reputation: 62603
No, it is certainly not enough. Is your class correctly following rule of 5? I.e. do you have properly defined or deleted copy constructor, assingment operator, move constructor and move assingment? Are you really ready to manage this pointer yourself?
I have two solutions for you.
Person
, rather than the object of type Person
. Are you calling Person
s members polymorphically? Use non-pointers unless you have to.std::unique_ptr
should be your first stop, and if you are sure shared ownership is required, use std::shared_ptr
.Upvotes: 6