3

I am implementing a custom iterator for a library, and am overloading the operators ++ and --. My prefix operators for these work perfectly, but my post operators cause memory leaks.

avl_iterator& operator++()
    {
        _node = utilities::next_node( _node );
        return (*this);
    }
avl_iterator& operator ++( int ) {
        avl_iterator temp(*this);
        ++(*this);
        return(temp);
    }

avl_iterator& operator -- () {
        _node = utilities::prev_node( _node );
        return (*this);
    }

avl_iterator& operator -- ( int ) {
        avl_iterator temp(*this);
        --(*this);
        return(temp);
    }

I realize that this is because I am returning a temporary variable, but I can't seem to think (or find) a better way of doing this.

S Grimminck
  • 516
  • 4
  • 21

1 Answers1

4

Returning a temporary variable is perfectly fine: it will get copied back to the caller, and the original one will be deallocated. It becomes an issue only when the class is not managing its resources properly.

The reason your solution has a problem is because it does not return a copy, but returns a reference to a local variable temp, which is undefined behavior.

To fix the problem, you should change your post-increment/decrement operators to

avl_iterator operator -- ( int ) {
    avl_iterator temp(*this);
    --(*this);
    return(temp);
}

and

avl_iterator operator ++( int ) {
    avl_iterator temp(*this);
    ++(*this);
    return(temp);
}

Note that having to copy is a major reason behind a widely circulated advise to prefer pre-increment/decrement operators on iterators to their post-increment/decrement counterparts.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523