简体   繁体   中英

Iterator and const_iterator operator++ post and prefix

We are working on a custom List class. We are trying to implement iterator and const_iterator and its functions but we have a problem with our ++operators. PostFix doesn't work at all, and PreFix gives us segfault when we step too far (the current code is a workaround that just returns the last valid result). Question1: How can we fix the segfault related to prefix without returning last valid element? (we have tried returning nullptr).

Postfix just wont iterate, even though we have followed every guide on the internet <.<

Question2: Why doesn't PostFix work?

Code for post&prefix:

List_const_iterator_& operator++()
  {
    if(ptr->next_ != nullptr)
    {
        ptr = ptr->next_;
        return *this;
    }
    else
        return *this;
  }

  List_const_iterator_ operator++(int unused)
  {
    List_const_iterator_ temp(*this);
    if(ptr->next_ != nullptr)
    {
      ptr = ptr->next_;
      return temp;
    }
    else
      return *this;
  }

Testcode (atm with postfix):

List<int> list1 {324, 2, 3};
  List_const_iterator_<int> clst = list1.cbegin();
  clst = clst++;
  cout << "val: " << clst.ptr->data_ << endl;
  clst = clst++;
  cout << "val2: " << clst.ptr->data_ << endl;
 clst = clst++;
  cout << "val3: " << clst.ptr->data_ << endl;

Output for postfix:

val: 324
val2: 324
val3: 324

Output for prefix:

val: 2
val2: 3
val3: 3  <-- This is where we segfault if we don't use the controll.

Try with just :

clst++;

instead of :

clst = clst++;

The latter resets clst to its original value (as if the increment didn't happen).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM