简体   繁体   English

将指针与引用进行比较

[英]Compare pointer with reference

I am refactoring a legacy code.我正在重构遗留代码。 I have to compare a pointer with reference for equality (To check whether both objects are equal).我必须比较一个指针与引用是否相等(检查两个对象是否相等)。 This question in SO does it by comparing the address. SO中的这个问题是通过比较地址来完成的。 if I do the same for pointer and reference as below, would there be any issues (any exceptional cases?).如果我对指针和引用执行如下相同的操作,会不会有任何问题(任何例外情况?)。 So far in my testing, it's working properly.到目前为止,在我的测试中,它工作正常。 Please advice请指教

#include <stdio.h>
#include <iostream>

class MemberData
{
    //Huge class with many data members
};

int main()
{
    MemberData  x ;
    const MemberData& y = x;
    MemberData *ptr= &x;


    if(std::addressof(*ptr)==std::addressof(y))
    {
            std::cout << "Both are equal" << "\n";  
    }

    return 0;
}

std::addressof(*ptr) seems redundant. std::addressof(*ptr)似乎是多余的。 If you have a pointer to the object, and you need a pointer to the object, then why indirect through the pointer and then get the pointer to object that was being pointed at?如果您有一个指向对象的指针,并且您需要一个指向该对象的指针,那么为什么要间接通过该指针然后获取指向所指向对象的指针呢? ptr == std::addressof(y) should work just as fine. ptr == std::addressof(y)应该可以正常工作。 As long as you want to compare equality of the address...只要你想比较地址的相等性...

(To check whether both objects are equal) (检查两个对象是否相等)

Comparing equality of addresses is comparing identity, ie whether they are the same object.比较地址的相等性就是比较身份,即它们是否是同一个对象。 To compare equality of objects, you'd generally compare their value.要比较对象的相等性,您通常会比较它们的值。 For example, following variables are not the same object and thus do not have the same address, but they are equal in value (assuming sane copy constructor):例如,以下变量不是同一个对象,因此没有相同的地址,但它们的值相等(假设有健全的复制构造函数):

MemberData x;
MemberData y = x;

The code you provide will always print the "Both are equal" because what you did is checking the address of x and the address of an alias of x, which is of course the same.您提供的代码将始终打印“两者相等”,因为您所做的是检查 x 的地址和 x 的别名地址,这当然是相同的。 The real question is do you just wanna check the equality of address instead of their inner members, ie two objects with different address but the same class with the same values.真正的问题是您是否只想检查地址的相等性而不是它们的内部成员,即具有不同地址但具有相同值的相同类的两个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM