I have a C ++ class that acts like a container: it has member functions size()
and operator[]
. The values ββstored in the container are std::tuple
objects. However, the container does not actually store tuples in memory; instead, it creates them on demand based on basic data stored in a different form.
std::tuple<int, int, int> MyContainer::operator[](std::size_t n) const {
Therefore, the return type operator[]
is a temporary object, not a reference. (This means that this is not an lvalue value, so the container is read-only, this is normal.)
Now I am writing an iterator class that can be used to move tuples in this container. I would like to model a RandomAccessIterator , which depends on the InputIterator , but the InputIterator requires support for the expression i->m
(where i
is an iterator instance), and as far as I can tell, the operator->
function is required to return the pointer.
Naturally, I cannot return a pointer to a temporary tuple constructed on demand. One possibility that comes to mind is to put an instance of the tuple in the iterator as a member variable and use it to store a copy of any value that the iterator currently occupies:
class Iterator { private: MyContainer *container; std::size_t current_index;
However, updating the stored value requires the iterator to check whether its current index is smaller than the size of the container, so that the past end iterator does not cause undefined behavior by accessing the end of the underlying arrays. This adds (a small amount) of overhead at runtime - not enough to make a decision inappropriate, of course, but it seems a little inelegant. An iterator does not need to store anything but a pointer to its iteration of the container and the current position inside it.
Is there a clean, well-established way to support operator->
for types of iterators that build their values ββon demand? How could other developers do this?
(Note that I donβt need to support operator->
- I implement the iterator basically so that the container can be moved using C ++ 11 β range for β, and std::tuple
does not have any members that usually would like to get through ->
anyway. But I would like to model the iterator concepts correctly, it seems to me that I cut corners differently. Or am I just not tired?)