Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing a reference

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?

like image 837
Meme Master Avatar asked Mar 12 '23 17:03

Meme Master


1 Answers

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.

like image 174
R Sahu Avatar answered Mar 16 '23 11:03

R Sahu