1

I am new to C++ and I'm trying to understand how this piece of code works.

~List() {
    for(auto& i : nodes) {
        delete &i;
    }
}

I have made a Simple Linked List class that has a vector of nodes.

What I am trying to understand is, if I delete the current node, how does the for each loop know where the next node is?

How I thought it would work is, I would store a pointer to the next node and delete the current one, and repeat this process until the next node is nullptr.

(Maybe my understanding of vectors is not complete or I don't understand how for-each loops work.)

Can someone who understands how this code works please explain what is going on here?

Saumi
  • 67
  • 3

1 Answers1

4
for(auto& i : nodes) { delete &i; }

is syntactic sugar for roughly

auto&& range = nodes;
for(auto it = std::begin(range); it != std::end(range); ++it)
{
    auto& i = *it:
    delete &i;
}

You're just iterating over nodes. Assuming that the destructor of i doesn't affect nodes, then there's no issue with your code.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • RIGHT!! My thinking was flawed. I thought we were going to the next node by looking at i.next, but we at going to the next node through the vector... – Saumi Jul 01 '19 at 10:45