I understand the normal operator overloading. Compiler can translate them to method call directly. I am not very clear about the -> operator. I was writing my first custom iterator and I felt like the need of -> operator. I took a look at the stl source code and implemented my own like it:
MyClass* MyClassIterator::operator->() const
{
//m_iterator is a map<int, MyClass>::iterator in my code.
return &(m_iterator->second);
}
Then I can use an instance of MyClassIterator like:
myClassIterator->APublicMethodInMyClass().
Looks like the compiler does two steps here.
1. Call the ->() method the get a temporary MyClass* variable.
2. Call the APublicMethodInMyClass on the temp variable use its -> operator.
Is my understanding correct?
is nothing but the following:
The first call to the overloaded
operator->gets you a pointer of some type which has an accessible (from your call-site) member function calledAPublicMethodInMyClass(). The usual function look-up rules are followed to resolveAPublicMethodInMyClass(), of course, depending on whether it is a virtual or not.There is not necessarily a temporary variable; the compiler may or may not copy the pointer returned by
&(m_iterator->second). In all probability, this will be optimized away. No temporary objects of typeMyClasswill be created though.The usual caveats also do apply to
m_iterator— make sure that your calls do not access an invalidated iterator (i.e. if you are usingvectorfor example).