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.
Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.
pointers are just like usual objects, they store a value inside, thus they refer to the stored values in them. "Dereferencing" is when we "disable" this connection to the usual value within and use the identifier of p to access/refer to a different value than the value stored in p .
We can use the addressoperator to obtain its address, whatever it may be. This address can be assigned to a pointervariable of appropriate type so that the pointer points to that variable. The dereference operator (*) is a unary prefix operator that can be used with any pointer variable, as in *ptr_var.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With