6

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.

Kangyabing
  • 61
  • 1

2 Answers2

7

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, RandomAccessIterators).

Community
  • 1
  • 1
Rapptz
  • 20,807
  • 5
  • 72
  • 86
3

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765