Narek
Narek

Reputation: 39881

const_iterator vs iterator for std::list

Is there any major difference between const_iterator and iterator implementations for std::list except operator* and operator->. Below you can see my non-templated homework-style example to show the gist. As much as I understand the rest of the methods just copy each-other for these classes, such as CTOR, operator==, operator!=, operator++, operator++(int), operator--, operator--(int).

class iterator
{
private:
    Node* m_node;

public:
    iterator(Node* node)
        : m_node(node)
    {

    }

    int& operator*()
    {
        return m_node->value;
    }

    Node* operator->()
    {
        return m_node;
    }

 ....
}

Now const iterator implementation

class const_iterator
{
private:
    Node* m_node;

public:
    const_iterator(Node* node)
        : m_node(node)
    {

    }

    int operator*() const
    {
        return m_node->value;
    }

    const Node* operator->() const
    {
        return m_node;
    }
......
}

If this is the major difference, then we should handle the duplication too, right?

Upvotes: 1

Views: 789

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

You are missing a few things described below, and the class is not "templetized" yet, but the approach is the same as what one implementation of the Standard Template Library is using.

  • Both iterators need a default constructor - this provides a way to make a null iterator, which you can assign later
  • const_iterator must be constructible from iterator - Add a constructor to const_iterator to accept "regular" iterator.

As far as code duplication is concerned, this is a fair observation indeed. However, most implementations fit on a single line, and return different types, so trying to share implementations across the two templates would make the code harder to read.

Upvotes: 2

Related Questions