问题描述
如果 p> m
只是(* p).m $ c $的语法糖, c>?基本上,我已经写的每个
operator->
可以实现如下:
Wouldn't it make sense if p->m
was just syntactic sugar for (*p).m
? Essentially, every operator->
that I have ever written could have been implemented as follows:
Foo::Foo* operator->()
{
return &**this;
}
是否有任何我想要 p- > m
表示(* p).m
?
Is there any case where I would want p->m
to mean something else than (*p).m
?
推荐答案
operator->()
具有隐含地重复调用的奇怪区别返回类型允许。显示这个的最清楚的方法是使用代码:
operator->()
has the bizarre distinction of implicitly being invoked repeatedly while the return type allows it. The clearest way to show this is with code:
struct X {
int foo;
};
struct Y {
X x;
X* operator->() { return &x; }
};
struct Z {
Y y;
Y& operator->() { return y; }
};
Z z;
z->foo = 42; // Works! Calls both!
我记得有一种情况是需要这种行为来使对象能够作为另一个对象的代理在一个智能指针的上下文中,虽然我不记得细节。我记得的是,我只能通过使用 a-> b
语法,通过使用这个奇怪的特殊情况,获得正常工作的行为;我找不到一个办法让(* a).b
工作类似。
I recall an occasion when this behaviour was necessary to enable an object to behave as a proxy for another object in a smart-pointer-like context, though I can't remember the details. What I do remember is that I could only get the behaviour to work as I intended using the a->b
syntax, by using this strange special case; I could not find a way to get (*a).b
to work similarly.
不确定回答你的问题;真的我在说,好问题,但它甚至比那更糟糕!
Not sure that this answers your question; really I'm saying, "Good question, but it's even weirder than that!"
这篇关于为什么operator->手动重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!