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?
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.
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.
++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)
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 --.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With