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?
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