Reputation: 3101
Sometimes I used &*it
to get a raw pointer from an iterator. But this doesn't always work when I'm using interator-debugging, consider getting a raw pointer of &*myVec.end()
. AFAIK there's a templated C++20 function to get an address from an iterator, but I can't remember it anymore. Can anyone help me ?
Upvotes: 2
Views: 640
Reputation: 473242
For any iterator i
which is a contiguous_iterator
, the expression to_address(i)
shall result in a pointer to a location in the range of the iterator, or a past-the-end pointer if it is the past-the-end iterator of the range. This can be provided via a specialization of pointer_traits<I>
for the iterator type I
, but for many iterators, calling operator->()
is adequate to the task.
This is only supported for contiguous iterators because... well, it doesn't make much sense otherwise. Assuming we're talking about a C++20 iterator that is not a proxy iterator (ie: reference
is exactly value_type&
), it is possible to get a pointer to the underlying value. But there is no requirement that the end iterator give you a pointer that is in any way meaningful.
This is only meaningful for contiguous iterators, because contiguous iterators have to point to an actual C++ array of value_type
s. As such, there is a pointer which is a past-the-end pointer to that array. Even if you could extract some kind of pointer from the end iterator of a non-contiguous iterator, it wouldn't be meaningful because non-contiguous iterators don't (necessarily) point to arrays.
So if you're working with a non-contiguous iterator, just use &*i
. It won't work on non-dereferenceable iterators, but nothing could work on those, since there's no pointer it could return.
Upvotes: 3