I'm doing a project for the university and im trying to find out how to delete memory properly and if the way of deleting that i came up with will have the same effect as using smart pointer.
This is a class that will hold all employees working in the company and teams which basically have vector of pointers to some of the employees.
class Company
{
private:
std::string companyInfo;
std::vector<Employee * > employees;
std::vector<Team *> teams;
public:
Company();
~Company();
std::string getCompanyInfo() const;
void setCompanyInfo(const std::string & companyInfo);
bool addEmployee(Employee * employee, const std::string & teamName);
bool addTeam(Team * team);
void printTeams() const;
void printEmployees() const;
};
So my question is : Is this a proper way of freeing the memory and if its is will it provide the same result as using smart pointers to automate the process.
Company::~Company()
{
for (Employee * e : employees) {
delete e;
}
employees.clear();
for (Team * t : teams) {
delete t;
}
teams.clear();
}
If it's better practise to use smart pointer should i use unique or shared pointer in my particular case. I have red about smart pointers and that they delete the allocated memory when the scope end but i'm really confused when will end. Is this going to happen when the destructor of company is called?
Thanks in advance and sorry if my questions look stupid.
unique_ptrwould be better, but why are you using pointer in the first place? Why not e.g. juststd::vector<Employee>? - lisyarusstd::vector<Employee>is your friend. - Swordfishstd::vector<Employee> employees;. Just make sure that both get removed when fired ^^ - Swordfish