nyr*_*yrl 7 c++ method-chaining operator-keyword
可能重复:
重载运算符 - >
嗨,
我已经看到operator->()它在被评估后被链接(重新应用),例如:
struct Bar
{
Bar() : m_str("Hello world!") {}
const string* operator->() const { return &m_str; }
string m_str;
};
struct Foo
{
const Bar& operator->() const { return m_bar; }
Bar m_bar;
};
int main()
{
Foo f;
cout << f->c_str() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
工作得很好,这需要三个operator->()进行评估- Foo::operator->(),Bar::operator->()和普通指针分辨率.
但它不适用于中间的Foo::operator->()指针- 如果返回指向Bar而不是引用的指针,它就不会编译.auto_ptr<auto_ptr<string>> 例如,同样如此.
它是否特定于非重载,operator->()因此它只应用一次而不会导致链接?可以在不使用的情况下使代码低于工作(*ptr2)-> ...吗?
int main()
{
string s = "Hello world";
auto_ptr<string> ptr1(&s);
auto_ptr<auto_ptr<string> > ptr2(&ptr1);
cout << ptr1->c_str() << endl; // fine
cout << ptr2->c_str() << endl; // breaks compilation
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Che*_*Alf 19
C++ 98标准§13.5.6/ 1"类成员访问":
表达式
x->m被解释为类型为if(x.operator->())->m的类对象x,以及是否通过重载解析机制在最佳匹配函数中选择运算符(13.3).TT::operator->
这在实践中意味着什么时候x是一个指针,你不会被链接; 然后你得到内置的operator->(即x->m用x指针转换(*x).m).
但是什么时候x是类类型的对象T,那么你可以获得链接效果.因为那时的解释(x.operator->())->m可以是(x.operator->())本身是一些类的对象,比如类U.那么第二个->可以解析为U::operator->,依此类推,如果它的结果再次是类类型对象...
就像,在你的情况下,Foo::operator->生成(引用)类的对象Bar,它确实定义了一个operator->.
但是当operator->返回一个指针时,例如std::auto_ptr<T>::operator->,它只是使用的内置operator->.
顺便说一句,链接可用于实际上防止某人使用delete不当.std::auto_ptr不这样做.我从来没有见过它.
但是在[comp.lang.c ++.moderated]中曾经有过一篇关于如何防止无意中delete由智能指针管理的原始指针的讨论线程,这是讨论过的一种可能性.
干杯和hth.
| 归档时间: |
|
| 查看次数: |
4005 次 |
| 最近记录: |