gpt4 book ai didi

c++:实现相等方法——如何确保给定对象与此引用不同?

转载 作者:可可西里 更新时间:2023-11-01 15:03:31 25 4
gpt4 key购买 nike

考虑以下代码片段:

bool SomeObject::equal(const SomeObject& rhs) const
{
if (this == &rhs)
{
return true;
}

// check the state
}

此代码的问题是 SomeObject 可能会覆盖 operator&(或者将来有人可能会添加它),这反过来可能会破坏此实现。

是否可以测试 rhs*this 是否是同一个对象而不受 operator& 实现的支配?

最佳答案

如果您想获取对象的实际地址并忽略重载的 & 运算符,请使用 std::addressof

bool SomeObject::equal(const SomeObject& rhs) const
{
if (this == std::addressof(rhs))
{
return true;
}

// check the state
}

引用:http://en.cppreference.com/w/cpp/memory/addressof

关于c++:实现相等方法——如何确保给定对象与此引用不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8821936/

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