gpt4 book ai didi

c++ - 为什么是 "dumb to override the & operator and return *this*"?

转载 作者:太空狗 更新时间:2023-10-29 19:59:05 25 4
gpt4 key购买 nike

当然,我想不出有什么理由让我想要覆盖一元&运算符,但在https://stackoverflow.com/a/4542813/368896中张贴者指出,关于某些类 X:

...unless X does something really dumb, like overloading the unary & to return this

(注意:我假设此评论指的是 & 运算符返回 this 的事实,而不是覆盖 & 运算符的事实本身。)

当我想到那个评论时,我突然想到“返回这个”正是 & 运算符所做的 - 即使在多重继承的情况下也是如此。 p>

鉴于人们可能永远不想覆盖一元&运算符,尽管如此,让它返回this(如果你确实决定覆盖它)?

最佳答案

it occurred to me that "returning this" is exactly what the & operator does

你说得对,尽管 C++ 也禁止获取临时对象的地址

the question you reference 的上下文中,这是关于确定一个对象是否是临时的:

如果您实现自己的返回 thisoperator &,您将通过告诉编译器 &(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&
}

关于c++ - 为什么是 "dumb to override the & operator and return *this*"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15464731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com