Strange bug with iterators

J

Juha Nieminen

I have this piece of (C++11) code:

//----------------------------------------------------------------------
#include <iterator>

template<typename Iter_t>
struct RangeWrapper
{
Iter_t mBegin, mEnd;
RangeWrapper(Iter_t b, Iter_t e): mBegin(b), mEnd(e) {}
Iter_t begin() { return mBegin; }
Iter_t end() { return mEnd; }
};

template<typename Container_t>
RangeWrapper<typename Container_t::reverse_iterator>
revRange(Container_t container)
{
return { container.rbegin(), container.rend() };
}


#include <vector>
#include <iostream>

int main()
{
std::vector<int> v = { 1, 3, 5, 7, 9 };

for(int i: revRange(v)) std::cout << " " << i;
std::cout << "\n";
}
//----------------------------------------------------------------------

For some reason it does not work properly when compiled with gcc 4.6.3.
It prints the first numbers ok, but then it starts printing zeros.

If I compile with -D_GLIBCXX_DEBUG I get a strange runtime error:

/usr/include/c++/4.6/debug/safe_iterator.h:142:error: attempt to copy-
construct an iterator from a singular iterator.

I don't understand what that means.

When run with gdb, the backtrace indicates that the error seems to
happen in RangeWrapper::begin().
 
J

jacob navia

Le 18/05/12 20:15, Juha Nieminen a écrit :
Ah, the bug was here. My bad.
????
Can you explain what was the bug, why it was there and how you fixed it?
 
A

Anand Hariharan

????
Can you explain what was the bug, why it was there and how you fixed it?

It should have been -

revRange(Container_t & container)

^^^

Since a the container was passed by value, the iterators that were
returned were that of the generated copy, not the intended container.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top