Reputation: 61
I read STL and a usage of pointer puzzles me.
destroy(&*first);
first is a pointer, then "&*first" is equal to first, why not use first directly? destroy is declared as follow:
void destroy(T* pointer)
T is a template parameter.
Upvotes: 6
Views: 805
Reputation: 320739
If the argument is already a raw pointer, then &*
combination does nothing, as you already noted. However, if the argument is a class type with overloaded unary *
operator, then &*
is no longer a no-op.
The classic usage of &*
pattern is to convert a "generic" pointer into a raw pointer. For example, if it
is an iterator associated with a vector element, then &*it
will give you an ordinary raw pointer to that vector element.
Upvotes: 3
Reputation: 21317
This is most likely due to operator overloading. first
is the name typically given to iterators, which overload operator*
to return a reference to the pointed to element of the container then operator&
is used to get the address of the variable the iterator was pointing to. You can read more about iterators here.
However, if first
is a pointer and not a user defined iterator, then yes you can just use first
directly. Note that pointers can be iterators (specifically, RandomAccessIterator
s).
Upvotes: 7