Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(*it)->method() vs (**it).method

When iterating over an vector (or other container) of pointers, is there any difference between and/or over advantage using:

for (it = v.begin(); it != v.end(); ++it) {
    (*it)->method();
}

or

for (it = v.begin(); it != v.end(); ++it) {
    (**it).method();
}
like image 246
Ross Avatar asked Nov 08 '12 19:11

Ross


1 Answers

In the C language, there is no difference. However, in C++, the -> operator can be overloaded, whereas the member selection . operator cannot.

So in (*foo)->bar *foo could designate a class object which acts as a smart pointer, though this won't happen if foo is an iterator over a standard C++ container of pointers, which means that *foo evaluates to a pointer.

And in (**foo).bar, **foo has to be a class object with a member called bar (which is accessible).

The unary * can also be overloaded (which is how the iterator foo, a class object, returns the object which it references).

In other words, the expressions can diverge in meaning, but if *foo is a pointer to a class/struct, then the equivalence inherited from the C language applies: (*ptr).member is equivalent to ptr->member.

like image 116
Kaz Avatar answered Sep 21 '22 10:09

Kaz