考虑以下代码片段:
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
}
关于c++:实现相等方法——如何确保给定对象与此引用不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8821936/