Home > front end >  Weird behavior dereferencing std::list iterator
Weird behavior dereferencing std::list iterator

Time:06-10

I am running into strange behavior when using std::list<std::array<T>>::iterator.

I'm trying to run the following code:

#include <iostream>
#include <list>
#include <array>
#include <algorithm>

using namespace std;

struct S {
    uint64_t x;    
};

#define N 10000

typedef array<S, N> block;
typedef list<block>::iterator it;

int main() {
    list<block> l;
    l.emplace_back();
    block& b = l.front();
    it i = l.begin();
    l.emplace_back();
    std::cout << i->data() << " " << b.data() << "\n";
    b = *(  i);
    std::cout << i->data() << " " << b.data() << "\n";
}

It gives me the following output:

0x55c2b63cbec0 0x55c2b63cbec0
0x55c2b63df760 0x55c2b63cbec0

When accessing the .data() through the iterator, it correctly points to the next element. However, dereferencing the incremented iterator gives me a reference to the same old element. I have been scratching my head over this for some hours now. Am I doing something wrong or misunderstanding how iterators work?

When I try the same code but with just list<int>, it works as expected.

    list<int> l;
    l.emplace_back(0);
    int& b = l.front();
    list<int>::iterator i = l.begin();
    l.emplace_back(1);
    std::cout << *i << " " << b << "\n";
    b = *(  i);
    std::cout << *i << " " << b << "\n";

Produces the expected output:

0 0
1 1

CodePudding user response:

The variable b is declared as a reference

block& b = l.front();

So in this statement

b = *(  i);

the second element of the list is assigned to the first element of the list.

So in this statement

std::cout << i->data() << " " << b.data() << "\n";

there are outputted values of returned by the member function data for the second element of the list and the first element of the list.

In the second example there is returned the same integer value that was assigned to the first element of the list.

You could get in the first program a similar result as in the second program if instead of using the member function data you would try to output values of arrays (provided that they are initialized for visibility).

  • Related