Dan*_*aum 3 c++ operator-overloading
当然,我想不出任何我想要覆盖一元运算&符的原因,但在/sf/answers/317996941/中,海报说明了某些类X:
...除非X做了一些非常愚蠢的事情,比如超载一元并且返回这个
(注意:我认为这个评论指的是&操作员返回this的事实,而不是覆盖&操作员本身的事实.)
正如我想过评论,它发生,我认为"回归这" 究竟该怎样&操作呢-即使是在多重继承的情况下.
鉴于人们可能永远不想覆盖一元运算&符,但是为什么让它返回是愚蠢的this(如果你决定覆盖它)?
在我看来,"返回这个"正是&运营商所做的
你是对的,尽管C++也禁止获取临时对象的地址.
在您引用的问题的上下文中,这是关于确定对象是否是临时的:
如果您实现了自己的operator &返回this,则通过告诉编译器&(expression)始终有效来绕过此保护.考虑:
struct foo
{
};
struct bar
{
bar* operator&()
{
return this;
}
};
template <typename T>
void test(const T*)
{
// no temporaries, can't take address of temporary...right?
}
int main()
{
foo x;
test(&x); // okay, x is an lvalue
/*
test(&(foo())); // not okay, cannot take address of temporary
*/
bar y;
test(&y); // still okay, y is an lvalue
test(&(bar())); // huh?! not taking address of temporary, calling operator&
}
Run Code Online (Sandbox Code Playgroud)