箭头->运算符重载在C ++内部工作? [英] How arrow-> operator overloading works internally in c++?
问题描述
我了解正常的运算符重载.编译器可以将它们直接转换为方法调用.我对->运算符不太清楚.我正在编写我的第一个自定义迭代器,感觉就像需要->运算符.我看了一下stl源代码,并实现了自己的代码:
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);
}
然后我可以使用MyClassIterator的实例,例如:
Then I can use an instance of MyClassIterator like:
myClassIterator->APublicMethodInMyClass().
看起来编译器在这里执行了两个步骤. 1.调用->()方法以获取一个临时MyClass *变量. 2.使用其->运算符在temp变量上调用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.
我的理解正确吗?
推荐答案
myClassIterator->APublicMethodInMyClass()
无非是以下内容:
myClassIterator.operator->()->APublicMethodInMyClass()
对重载的operator->
的第一次调用会为您提供某种类型的指针,该指针具有一个可访问的(从您的调用站点获取)成员函数,称为APublicMethodInMyClass()
.当然,根据函数查找规则来解析APublicMethodInMyClass()
,具体取决于它是否是虚拟的.
The first call to the overloaded operator->
gets you a pointer of some type which has an accessible (from your call-site) member function called APublicMethodInMyClass()
. The usual function look-up rules are followed to resolve APublicMethodInMyClass()
, of course, depending on whether it is a virtual or not.
不一定有一个临时变量;编译器可能会也可能不会复制&(m_iterator->second)
返回的指针.很有可能,这将被优化掉.不过不会创建类型为MyClass
的临时对象.
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 type MyClass
will be created though.
通常的警告也适用于m_iterator
-确保您的调用不会访问无效的迭代器(例如,如果您使用的是vector
).
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 using vector
for example).
这篇关于箭头->运算符重载在C ++内部工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!