Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: calling member functions within constructor?

Tags:

c++

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;
}

Seems that the problem is in the constructor IntList(). Is it because it calls the member function begin()?

like image 951
powerboy Avatar asked Oct 26 '25 08:10

powerboy


2 Answers

Looks like You are inserting after end();

In the body of the constructor

IntList() { tail_ = begin(); }

the base class is constructed and it's members can be called, but for an empty list, it should return end();

like image 62
Maciej Hehl Avatar answered Oct 28 '25 22:10

Maciej Hehl


The documentation for slist<> indicates that the iterator provided to insert_after must be dereferenceable.

Since your list is empty the begin() returns end() and is thus not dereferenceable.

See documentation here:

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

iterator insert_after(iterator pos, const value_type& x)

pos must be a dereferenceable iterator in *this. (That is, pos may not be end().) Inserts a copy of x immediately following pos. The return value is an iterator that points to the new element. Complexity: constant time.

like image 39
Martin York Avatar answered Oct 28 '25 23:10

Martin York



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!