6

I'm reading "The C++ Programming Language (4th edition)" and I ran into this:

template<class C, class Oper>
void for_all(C& c, Oper op) // assume that C is a container of pointers
{
    for (auto& x : c)
        op(*x); // pass op() a reference to each element pointed to
}

So from what I understand, we're iterating through c and getting a reference to x, which is the current iteration. x is then passed to the function call operator of op, but it is dereferenced first? Why would x be dereferenced?

Meme Master
  • 147
  • 1
  • 2
  • 6
  • 4
    See the comment where it says that `C` is a container of pointers. Apparently `op()` doesn't want a pointer, it wants the value that the pointer points to. So you have to indirect. – Barmar Jul 15 '16 at 04:56
  • 1
    I Googled "dereferencing a reference" word for word after reading that same excerpt of code! Glad to see I'm not the only one who made this mistake. – hyrumcoop Jul 09 '21 at 06:13

1 Answers1

9

You said in a comment in the posted code:

// assume that C is a container of pointers

That means x is a reference to a pointer. *x evaluates to be the object that pointer points to.

op must expect an object or a reference to an object, not a pointer to an object.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    Well that explains it. By the way, the code is straight from the book and is not mine. I guess the comment went over my head. – Meme Master Jul 15 '16 at 05:00