gpt4 book ai didi

c++ - 检查两个 QSharedPointer 是否有相同的数据

转载 作者:搜寻专家 更新时间:2023-10-31 01:50:34 27 4
gpt4 key购买 nike

我有两个 QSharedPointer,我可以使用 operator== 来检查它们是否指向同一个对象

QSharedPointer1 == QSharedPointer2

或者我必须写

QSharedPointer1.data() == QSharedPointer2.data()

存储在指针中的对象重载了运算符==。

最佳答案

你应该使用operator==:

bool operator== ( const QSharedPointer & ptr1, const QSharedPointer & ptr2 )

Returns true if the pointer referenced by ptr1 is the same pointer as that referenced by ptr2. If ptr2's template parameter is different from ptr1's, QSharedPointer will attempt to perform an automatic static_cast to ensure that the pointers being compared are equal. If ptr2's template parameter is not a base or a derived type from ptr1's, you will get a compiler error.

因此,无需通过 data() 方法获取指针,+ 它将尝试执行 static_cast 以匹配模板参数。

另外,请注意,存储在指针中的对象是否重载了operator==并不重要——您只是在此处比较指针,而operator==是为指针类型定义。如果你想比较指针所引用的对象,你需要取消引用指针并比较对对象的引用(这将调用 T::operator== 方法):

if(*ptr1 == *ptr2)
// ...

关于c++ - 检查两个 QSharedPointer 是否有相同的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14879250/

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