gpt4 book ai didi

rust - 为什么指向同一分配的两个引用计数器不相等?

转载 作者:行者123 更新时间:2023-12-03 11:29:53 26 4
gpt4 key购买 nike

我最近在 the Rust documentation about the implementation of PartialEq for Rc 中遇到了这个问题:

/// If `T` also implements `Eq` (implying reflexivity of equality),
/// two `Rc`s that point to the same allocation are
/// never unequal.
根据定义,指向内存中两个相同位置的两个指针肯定是相等的(因为它们是相同的值)?如果两个值只有 PartialEq,为什么情况不会如此?而不是 Eq ?

最佳答案

Rust 的指针比较不比较指针,而是比较指向的值。 &T 就是这种情况, &mut T , Box<T> , Rc<T> , Arc<T>等,除了原始指针 *const T*mut T他们自己。这些智能指针通常有一个额外的方法(在这种情况下为 std::rc::Rc::ptr_eq )用于实际的指针比较。
这类似于 Debug在这些指针上打印指向的值而不是地址,您需要 Pointer打印实际地址的特征:Rust 不是很注重地址。
现在,如果您有一个类型,例如 f64没有传递性 == (也就是说,它实现了 PartialEq 但没有实现 Eq )并将其包裹在 Rc 中,你也得到非传递性:

fn main() {
let a = std::rc::Rc::new(std::f64::NAN);

println!("a == a?: {}", a == a);
println!(
"a == a but with pointer comparison?: {}",
std::rc::Rc::ptr_eq(&a, &a)
);

// But:
let answer = std::rc::Rc::new(42);
// surely this will have a different address
let another_answer = std::rc::Rc::new(42);

println!("answer == another_answer?: {}", answer == another_answer);
}
打印:
a == a?: false
a == a but with pointer comparison?: true
answer == another_answer?: true
T碰巧执行 Eq以及 PartialEq ,当前实现确实使用尚未稳定的特化功能进行指针比较。
也可以看看:
  • Why does Rust not implement total ordering via the Ord trait for f64 and f32?
  • 关于rust - 为什么指向同一分配的两个引用计数器不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62996290/

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