Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinterpret_cast an iterator to a pointer

I've got an iterator of Things. If I want to convert the current item to a pointer to the item, why does this work:

thing_pointer = &(*it);

But this not:

thing_pointer = reinterpret_cast<Thing*>(it);

This is the compiler error I'm trying to comprehend: http://msdn.microsoft.com/en-us/library/sy5tsf8z(v=vs.90).aspx

Just in case, the type of the iterator is std::_Vector_iterator<std::_Vector_val<Thing,std::allocator<Thing> > >

like image 548
Adam Millerchip Avatar asked Nov 29 '22 12:11

Adam Millerchip


1 Answers

In

&(*it);

the * is overloaded to do what you logically mean: convert the iterator type to its pointed-to object. You can then safely take the address of this object.

Whereas in

reinterpret_cast<Thing*>(it);

you are telling the compiler to literally reinterpret the it object as a pointer. But it might not be a pointer at all -- it might be a 50-byte struct, for all you know! In that case, the first sizeof (Thing*) bytes of it will absolutely not happen to point at anything sensible.

Tip: reinterpret_cast<> is nearly always the wrong thing.

like image 104
j_random_hacker Avatar answered Dec 05 '22 16:12

j_random_hacker