Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dereference a pointer and then take the address of dereference

Tags:

c++

pointers

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.

like image 211
Kangyabing Avatar asked Aug 10 '14 02:08

Kangyabing


People also ask

What happens when you dereference a pointer?

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.

How do we dereference a pointer?

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.

What is the difference between pointer and dereference?

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 .

What is dereference operator and address operator?

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.


2 Answers

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

like image 54
Rapptz Avatar answered Nov 15 '22 07:11

Rapptz


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.

like image 36
AnT Avatar answered Nov 15 '22 07:11

AnT