The use of delete

Hello I'm doing a program which use the memory dynamic , but i have a problem to use delete I'm going to show you a part of my code


1
2
3
4
5
6
7
void Bibliotheque::stocker(Oeuvre & test, int n=1 )  {
 	  while (n >=1){      
      list.push_back(new Exemplaire(test));
      n--;
      }
}

So here I'm basically stoking a vector of pointers which is call list
The vetor was previously declared in the class Bibliotheque in the private mebres:


private:

vector <Exemplaire*> list;


But I need to liberate the space of memory of list using a desctructor in the class Bibliotheque , so I made:

Bibliotheque::~Bibliotheque(){
for(unsigned int p=0;p<list.size();p++)
list.push_back(delete );
}


But i have an error in my compliler. So Any body could help me to do this?

Thanks for your help
instead of your loop:
1
2
3
4
while(!list.empty()) {
    delete list.back();
    list.pop_back();
}
Or you can use vector of smart pointers.
It works so well , but the only thing is theo order I need the first element of the vector at the beginning
and with this method i have the last one, but thanks i'm going to find the solution.
I need the first element of the vector at the beginning
They are deleted anyway. So, what the problem?

Other way:
1
2
3
4
5
6
7
8
void deleter(Exemplaire* c)
{
    delete c;
}

//in destructor
std::for_each(list.begin(), list.end(), deleter);
 list.clear();
If the order in which you need the elements stored is important, try using a deque (pronounced 'deck'). It's a handy C++ double-ended container and you can access the container from either end; unlike a vector which is a first-in-last-out container.

Hope that helps. :)
Another way
1
2
3
4
5
6
7
8
9
vector <Exemplaire> list;

list.push_back(Exemplaire(test)); //no new

Bibliotheque::~Bibliotheque(){
// no delete
}

~Bibliotheque() = default; //no code 


PS: don't forget about the copy constructor and the assignment operator
Last edited on
Topic archived. No new replies allowed.