I have the following class:
class list {
private:
struct node {
node() { data=T(); prev=next=this; }
˜node() {}
T data;
node *prev;
node *next;
};
public:
class iterator {
public:
iterator() : p(NULL) {}
T & operator*() { return p->data; }
iterator & operator++()
{ p = p->next; return *this; }
iterator & operator++(int)
{ iterator tmp = *this; ++*this; return *tmp; }
bool operator==(const iterator & rhs) const
{ return p == rhs.p; }
bool operator!=(const iterator & rhs) const
{ return p != rhs.p; }
private:
friend class list<T>;
iterator(node *p) : p(p) {}
node *p;
};
iterator begin() { return iterator(head->next); }
iterator end() { return iterator(head); }
list();
˜list();
etc ...
private:
int N;
node *head;
node *findnode(int);
};
I see that the begin() function returns a constructor for the iterator class. Does this mean that a new iterator is created when it is called? If so, will the memory be recycled after the variable that this iterator is assigned to goes out of scope? I'm slightly confused, for the iterator constructor has no return type. If someone could shed some light on my issues, I would be most appreciative.
Yes a new iterator is created when begin is called. At a high level, yes the memory the iterator occupies will be recycled after it goes out of scope.
Constructors do not have return types as they are called in place on the memory they are to initialize.
At a somewhat lower level, variables that are declared on the stack have their destructor called when they go out of scope, which is one aspect of "recycling". The memory they occupy is on the stack rather than in the heap (as it would be if new were called), so it doesn't get freed in the sense of doing a delete or garbage collection. Rather the memory the variable had occupied may sit idle for a while or be immediately overwritten depending on if stack frames are being removed or added immediately after it goes out of scope (i.e the functions are returning up the stack or new calls are being made).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With