Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing a C++ postfix increment operator

I compiled the following example:

#include <iostream>
#include <iterator>
using namespace std;

class myiterator : public iterator<input_iterator_tag, int>
{
  int* p;
public:
  myiterator(int* x) :p(x) {}
  myiterator(const myiterator& mit) : p(mit.p) {}
  myiterator& operator++() {++p;return *this;}
  myiterator& operator++(int) {myiterator tmp(*this); operator++(); return tmp;}
  bool operator==(const myiterator& rhs) {return p==rhs.p;}
  bool operator!=(const myiterator& rhs) {return p!=rhs.p;}
  int& operator*() {return *p;}
};

int main () {
  int numbers[]={10,20,30,40,50};
  myiterator beginning(numbers);
  myiterator end(numbers+5);
  for (myiterator it=beginning; it!=end; it++)
      cout << *it << " ";
  cout << endl;

  return 0;
}

from cplusplus.com/reference and I get the compiler warning:

iterator.cpp: In member function 'myiterator& myiterator::operator++(int)':
iterator.cpp:13: warning: reference to local variable 'tmp' returned

What's wrong here? Is the postfix signature supposed to be myiterator operator++(int) i.e. return by value?

Is there somewhere defined what the postfix signature should look like on STL iterators?

like image 354
chris Avatar asked Dec 03 '10 16:12

chris


People also ask

Can we write ++ i ++ in C program?

Master C and Embedded C Programming- Learn as you go That means both i++ and ++i will be equivalent. i=5 ++i; printf("%d",i); both will make i=6. However, when increment expression is used along with assignment operator, then operator precedence will come into picture.

How does a postfix increment operator work?

The effect of applying the postfix increment operator (++) is that the operand's value is increased by one unit of the appropriate type. Similarly, the effect of applying the postfix decrement operator (--) is that the operand's value is decreased by one unit of the appropriate type.

What is i ++ and ++ i explain with an example?

++i will increment the value of i , and then return the incremented value. i = 1; j = ++i; (i is 2, j is 2) i++ will increment the value of i , but return the original value that i held before being incremented. i = 1; j = i++; (i is 2, j is 1)

Is A ++ a postfix operator?

Postfix operators are unary operators that work on a single variable which can be used to increment or decrement a value by 1(unless overloaded). There are 2 postfix operators in C++, ++ and --.


1 Answers

Is there somewhere defined what the postfix signature should look like on STL iterators?

The Standard.

The Standard dictates such things. In the case of this operation, the standard basically says "you have to return something that is convertible to const X&" where X is the iterator. In practice, this means you can return by reference if that applies to you (it doesn't), or return by value.

See 24.1.3/1

like image 193
John Dibling Avatar answered Oct 01 '22 05:10

John Dibling