Re: deleting pointers in a list.
bejiz <bruno.julier@wanadoo.fr> wrote:
class linked_list
{
public:
linked_list(): p_begin(0), p_end(0) {};
~linked_list(){};
You'd probably want to call clear() from destructor.
void clear( linked_list A)
Why does clear() take a parameter? It's a method of linked_list - =
shouldn't it work on the instance it's called on?
Also, it takes its parameter by value, meaning it works on a copy of =
linked_list. But it's a shallow copy - you now have two instances of =
linked_list whose p_begin and p_end members point to the same set of =
nodes. You delete those nodes and update p_begin and p_end in the =
temporary copy of linked_list, but the original remains unchanged: its =
p_begin and p_end members are now dangling pointers (pointing to data =
that's already been deallocated).
{
while(p_begin!=0)
{
Node* p_zap = new Node(0,0);
p_zap = A.p_begin;
You allocate a new instance of Node, make p_zap point to it - and then =
immediately make it point to something else. Thus, you leak that Node(0, =
0).
cout << " delete : " << p_zap->data << endl;
p_begin = p_begin->p_next;
delete p_zap;
}
You probably want to set p_end = NULL here, otherwise it still points =
to a now-deleted last node.
void push_back( const int& a)
No need to pass int by reference, just make it
void push_back(int a)
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not =
necessarily a good idea. It is hard to be sure where they are going to =
land, and it could be dangerous sitting under them as they fly overhead. =
-- RFC 1925