(* it) & # 8594; method () vs (** it). method

When repeating along a vector (or other container) of pointers, is there any difference between and / or advantage using:

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

or

 for (it = v.begin(); it != v.end(); ++it) { (**it).method(); } 
+7
source share
5 answers

There is no difference in C. However, in C ++, the -> operator can be overloaded, while the element select statement . can not.

Thus, in (*foo)->bar *foo one could designate a class object that acts as an intelligent pointer, although this will not happen if foo is an iterator over a standard container of C ++ pointers, which means that *foo evaluates pointer.

And in (**foo).bar , **foo should be an object of a class with a member called bar (which is available).

Unary * can also be overloaded (as the iterator foo , an object of the class, returns the object that it refers to).

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

+10
source

They are equivalent: as defined by the standard (for pointers)

5.2.5 Access to a member of the class [expr.ref]
2: for the first parameter (period), the first expression must have the full class type. For the second option (arrow), the first expression should have a pointer to the full type of the class. The expression E1-> E2 is converted to the equivalent form (* (E1)). E2 ; the rest of 5.2.5 will only address the first option (period) .65 In any case, the id expression must indicate a member of a class or one of its base classes.

Classes and operator overrides β†’ and * are not relevant here, since the container contains pointers.

Thus:

 (*it)->method(); // Is equivelent to: (*((*it))).method(); // This is equivelent too: (**it).method(); // thus both expressions are identical in this context. 
+3
source

Not. -> just says to access the structure as a pointer. . acts as if it is just a structure. It is syntactic - there is no difference in functionality.

Edit: you can overload -> to do something else, although it is assumed that you are not doing the same. You don’t know why you did this, but if you did, you would have to dereference your structure again using the optional * .

+2
source
They are the same. You can use one or another option depending on the coding conventions you use. Operators

-> and * can be overloaded while the operator . can not.

0
source

In Ubuntu 12.04, a list iterator is implemented as follows:

 template<typename _Tp> struct _List_iterator { // ... reference operator*() const { return static_cast<_Node*>(_M_node)->_M_data; } pointer operator->() const { return std::__addressof(static_cast<_Node*>(_M_node)->_M_data); } // ... 
0
source

All Articles