I am looking for some help regarding the pointer dereference operator -> . Let me describe what I am trying to do.
I am implementing a unidirectional iterator for a special container. The container is special in the sense that it does not physically allocate any space for the contained values but generates them at run time on demand. For example, consider that the container is “M consecutive integral multiples of N“.
Since I do not want to store the value directly in my iterator, I create a value on the heap on demand.
When I need a pointer to the value I delete the old one if it’s out-of-date and create a new one. This means that invocation of operator *() or operator ->() may delete an old value and new a new value, if the iterator has been advanced with operator ++() after they were last invoked.
Now I would like to use a smart_ptr to point at my value rather than keep a native pointer around. In order to do so I realize I need to understand the semantics of the -> operator better.
- First of all, is
->a unary operator ? - If that be so, how does
i->memberwork. This would translate to(pointer returned)member, which is not a syntactically valid form. - “member” could be a data member or a member function.
->()smells more like a binary operator that executes(*pointer returned).member. Since “member” is not a value, such a semantics is not equivalent to a binary operator either.- What happens to the pointer returned by
->()? who is supposed to own it ? - How can I use RAAI in this framework ? Is reference counted pointers the only option ?
- There is no
--operator for this iterator so i don’t need to keep the previous values around
Thanks for your responses. Ending with a meta question, should this be a wiki ?
Here is the answer to answer your questions, though I do not think they are so useful as you might hope:
memberis. Ifmemberisn’t a field/member of the class/struct pointed to be the return ofoperator ->then the compiler will complain.membercould indeed be either a data member or a member function.member. It’s there just to implement smart pointers. It is perfectly valid to sayreturn_type *ptr = smarptr.operator ->().operator ->for anything at all other than implementing a smart pointer I have no intentions of helping you write code that programmers after you will revile and make fun of.I question your desire to point at your value. It seems to me like you could hold it by value as a member value of your iterator, and I will give an example of how this could work below. But if you’re set on using a pointer to your value, and want to use a smart pointer, just return the result of
smartptr.operator ->()for your ownoperator ->(). You might also use the member function of your smart pointer (oftenget) that returns a ‘bare’ pointer and that would likely confuse people a little less.Here is a sample of how your example container should work: