Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a vector of pointers to objects. How to free memory?

Tags:

c++

For example:

class Airport : public vector<Airline*>

How do I free the memory properly? I would prefer not use smart pointers as I have not learned it yet in my course.

like image 817
user2158031 Avatar asked Oct 25 '25 05:10

user2158031


1 Answers

As others have pointed out, Airport should not inherit from vector. Airport should contain a vector. Then there is the question of who owns the Airlines, do you want the Airlines to be destroyed when the Airport is destroyed? If so I suggest either a simple std::vector<Airline>:

class Airport {
    std::vector<Airline> airlines_;
    //...
};

Or if you need polymorphism, i.e Airline is a base class with specializations for different Airlines I suggest smart pointers:

class Airport {
    std::vector<std::unique_ptr<Airline>> airlines_; 
    //...
};

If you really don't want to use smart pointers you could use raw pointers and then carefully delete them in the destructor:

class Airport {
    std::vector<Airline*> airlines_;
  public:
    Airport(const Airport&) = delete;             // not allowed
    Airport& operator=(const Airport&); = delete; // not allowed
   ~Airport() { 
        for (auto airline : airlines) {
            delete airline;
        }
    }
   //...
};

If you do this you need to think carefully about what copying behaviour you want Airport to have because the default copy constructor and assignment operator will not manage the memory properly. As a first step you can prevent copying by 'delete'ing copy constructor and assignment operator as I have above. But I suggest as soon as you learn about smart pointers use them instead as most of these problems go away.

If the Airport does not own the Airlines then store raw pointers or shared smart pointers in the vector and leave it to whoever owns the Airlines to free the memory properly. In my mind an Airline can operate in more than one Airport so it doesn't make sense for the Airport to own the Airline so there should be a separate container of Airline but it depends on your model.

like image 81
Chris Drew Avatar answered Oct 26 '25 19:10

Chris Drew