5

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?

Giacomo Tagliabue
  • 1,679
  • 2
  • 15
  • 31

3 Answers3

8

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.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • `I` is actually an iterator. This makes totally sense :) – Giacomo Tagliabue Dec 25 '12 at 23:56
  • If `I` is *just* a pointer, this doesn't make sense. Most likely it is a smart pointer (a class which "behaves" like a pointer). For a raw pointer, the `*` and `&` effectively cancel each others out. But for smart pointers, this is a way to get a *raw* pointer to the pointed-to object – jalf Dec 25 '12 at 23:59
2

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

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

perreal
  • 94,503
  • 21
  • 155
  • 181