C ++: calling member functions in constructor?

The following code raises a runtime error:

#include <iostream> #include <iterator> #include <ext/slist> class IntList : public __gnu_cxx::slist<int> { public: IntList() { tail_ = begin(); } // seems that there is a problem here void append(const int node) { tail_ = insert_after(tail_, node); } private: iterator tail_; }; int main() { IntList list; list.append(1); list.append(2); list.append(3); for (IntList::iterator i = list.begin(); i != list.end(); ++i) { std::cout << *i << " "; } return 0; } 

The problem seems to be with the IntList() constructor. Is it because it calls the begin() member function?

+3
c ++
source share
4 answers

It looks like you are pasting after end ();

In the body of the constructor

 IntList() { tail_ = begin(); } 

a base class is created and its members can be called, but for an empty list it should return end ();

+2
source share

Your problem is not in the constructor, but in the first call to append() . Since your list is empty begin() equals end() . end() is a valid iterator, but after that it is not. To solve this problem, try calling insert() instead.

Thus, a quick look at <ext/slist> confirms that the slist destructor slist not virtual, which means that slist not intended to be output from.

+2
source share

The documentation for slist <> indicates that the iterator provided for insert_after should be dereferenced.

Since your list is empty, begin () returns end () and therefore does not cause any differences.

See the documentation here:

 http://www.sgi.com/tech/stl/Slist.html 

Iterator insert_after (iterator pos, const value_type & x)

pos must be a dereferenced iterator in * this. (That is, pos cannot be end ().) Inserts a copy of x immediately after pos. The return value is an iterator that points to a new element. Difficulty: constant time.

+1
source share

.begin () is not valid if there are no elements in your collection.

0
source share

All Articles