osk
osk

Reputation: 810

Will a destructor be called if it is for an object in a vector?

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

Answers (1)

SergeyA
SergeyA

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.

  1. Do not use the pointer at all. From the code it is not clear why you need a pointer to Person, rather than the object of type Person. Are you calling Persons members polymorphically? Use non-pointers unless you have to.
  2. If you sure you need a pointer, use a pointer which manages itself. std::unique_ptr should be your first stop, and if you are sure shared ownership is required, use std::shared_ptr.

Upvotes: 6

Related Questions