I have a class. Let's call it House. Houses of various properties are contained in a registry. Let's call this house registry. Within this class, I want to add a vector containing pointers to different houses sorted in different ways(perhaps by name and number). Within this class, I have a function that creates new House objects and inserts them in the respective order. In doing so I'm leaving memory leaks as the program may terminate in a myriad of ways but doesn't free up memory stored in the vector. I know I can use smart pointers. But how do I implement them in the right way? I'm intentionally leaving out the destructor as its implementation is fairly obvious. But this question is specifically about smart pointers. A great answer would preferably include their implementation with comparators.
class HouseRegistry{
struct House{
....
}
private:
vector<House*>HousesbyName;
vector<House*>HousesbyNumber
bool newHouse(...){
House *somehouse = new House;
....
HousesbyName.insert(inserter,somehouse);
HousesbyNumber.insert(inserter2,somehouse);
return true;
}
}
CodePudding user response:
#include <vector>
#include <memory>
std::vector<std::shared_ptr<House>> HousesbyName;
std::vector<std::shared_ptr<House>> HousesbyNumber
auto somehouse = std::make_shared<House>();
...
HousesbyName.insert(inserter, somehouse);
HousesbyNumber.insert(inserter2, somehouse);
...
CodePudding user response:
How do I ensured all pointers are freed?
In general: By always freeing every dynamic allocation after you no longer need them.
The general answer is simple, and following it isn't easy. There are ways to make it easier in different cases. The easiest way is to not use dynamic allocation manually at all in the first place. Your example doesn't necessarily demonstrate a need for it. You could use std::vector<House>
to store the objects. Alternatively, your use cases seems appropriate for a multi-index container. The standard doesn't provide a multi-index container template, but Boost does.