Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing and dereferencing in the same instruction

Wondering through the LLVM source code i stumbled upon this line of code

MachineInstr *MI = &*I;

I am kinda newb in c++ and the difference between references and pointers is quite obscure to me, and I think that it has something to do about this difference, but this operation makes no sense to me. Does anybody have an explanation for doing that?

like image 995
Giacomo Tagliabue Avatar asked Dec 25 '12 23:12

Giacomo Tagliabue


3 Answers

The type of I is probably some sort of iterator or smart pointer which has the unary operator*() overloaded to yield a MachineInstr&. If you want to get a built-in pointer to the object referenced by I you get a reference to the object using *I and then you take the address of this reference, using &*I.

like image 60
Dietmar Kühl Avatar answered Nov 18 '22 07:11

Dietmar Kühl


C++ allows overloading of the dereference operator, so it is using the overloaded method on the object, and then it is taking the address of the result and putting it into the pointer.

like image 42
Ignacio Vazquez-Abrams Avatar answered Nov 18 '22 06:11

Ignacio Vazquez-Abrams


This statement:

MachineInstr *MI = &*I;

Dereferences I with *, and gets the address of its result with & then assigns it to MI which is a pointer to MachineInstr. It looks like I is an iterator, so *I is the value stored in a container since iterators define the * operator to return the item at iteration point. The container (e.g. a list) must be containing a MachineInstr. This might be a std::list<MachineInstr>.

like image 2
perreal Avatar answered Nov 18 '22 05:11

perreal