rust - 为什么用==比较两个看似相等的指针可以返回false?

标签 rust

我想测试两个类型的对象是否为 Rc<Trait>包含具体类型的相同实例,因此我比较指向内部对象的指针 Rc为了平等。如果所有代码都位于同一个 crate 中,它似乎可以正常工作,但当涉及多个 crate 时就会失败。

在 Rust 1.17 中函数 Rc::ptr_eq 添加了,从 Rust 1.31 开始,它表现出与此问题中使用的手动指针比较相同的跨箱问题。

这是 crate mcve 的实现( src/lib.rs ):

use std::rc::Rc;

pub trait ObjectInterface {}

pub type Object = Rc<ObjectInterface>;

pub type IntObject = Rc<i32>;

impl ObjectInterface for i32 {}

/// Test if two Objects refer to the same instance
pub fn is_same(left: &Object, right: &Object) -> bool {
    let a = left.as_ref() as *const _;
    let b = right.as_ref() as *const _;
    let r = a == b;
    println!("comparing: {:p} == {:p} -> {}", a, b, r);
    r
}

pub struct Engine {
    pub intval: IntObject,
}

impl Engine {
    pub fn new() -> Engine {
        Engine {
            intval: Rc::new(42),
        }
    }

    pub fn run(&mut self) -> Object {
        return self.intval.clone();
    }
}

我使用以下代码 ( tests/testcases.rs ) 测试实现:

extern crate mcve;

use mcve::{is_same, Engine, Object};

#[test]
fn compare() {
    let mut engine = Engine::new();

    let a: Object = engine.intval.clone();
    let b = a.clone();
    assert!(is_same(&a, &b));

    let r = engine.run();
    assert!(is_same(&r, &a));
}

运行测试结果输出如下:

comparing: 0x7fcc5720d070 == 0x7fcc5720d070 -> true
comparing: 0x7fcc5720d070 == 0x7fcc5720d070 -> false
thread 'compare' panicked at 'assertion failed: is_same(&r, &a)'

比较运算符==怎么可能返回 false虽然指针看起来是一样的?

一些观察:

  • 比较返回true当两个对象( ab )都在同一个 crate 中时。但是,比较返回 false当函数 r 返回其中一个对象 ( Engine::run ) 时,这是在另一个 crate 中定义的。
  • 当我将测试函数放入 lib.rs 中时,测试正确通过了.
  • 这个问题可以通过定义 struct Engine { intval: Object } 来解决。 ,但我仍然对原因感兴趣。

最佳答案

什么时候“指针”不是“指针”?当它是一个胖指针ObjectInterface 是一个特征,这意味着 &dyn ObjectInterface 是一个特征对象。 Trait 对象由两个 机器指针组成:一个用于具体数据,一个用于vtable,一组针对具体值的 trait 的特定实现。这种双指针称为胖指针。

使用夜间编译器和 std::raw::TraitObject ,您可以看到差异:

#![feature(raw)]

use std::{mem, raw};

pub fn is_same(left: &Object, right: &Object) -> bool {
    let a = left.as_ref() as *const _;
    let b = right.as_ref() as *const _;
    let r = a == b;
    println!("comparing: {:p} == {:p} -> {}", a, b, r);

    let raw_object_a: raw::TraitObject = unsafe { mem::transmute(left.as_ref()) };
    let raw_object_b: raw::TraitObject = unsafe { mem::transmute(right.as_ref()) };
    println!(
        "really comparing: ({:p}, {:p}) == ({:p}, {:p})",
        raw_object_a.data, raw_object_a.vtable,
        raw_object_b.data, raw_object_b.vtable,
    );

    r
}
comparing: 0x101c0e010 == 0x101c0e010 -> true
really comparing: (0x101c0e010, 0x1016753e8) == (0x101c0e010, 0x1016753e8)
comparing: 0x101c0e010 == 0x101c0e010 -> false
really comparing: (0x101c0e010, 0x101676758) == (0x101c0e010, 0x1016753e8)

事实证明(至少在 Rust 1.22.1 中)每个代码生成单元创建一个单独的 vtable!这解释了为什么当它们都在同一个模块中时它会起作用。有 active discussion关于这是否是错误。

当您使用 #[inline] 注释 newrun 函数时,使用者将使用该 vtable。


作为Francis Gagné said :

You can change as *const _ to as *const _ as *const () to turn the fat pointer into a regular pointer if you only care about the value's address.

这可以用 std::ptr::eq 清楚地表达出来:

use std::ptr;

pub fn is_same(left: &Object, right: &Object) -> bool {
    let r = ptr::eq(left.as_ref(), right.as_ref());
    println!("comparing: {:p} == {:p} -> {}", left, right, r);
    r
}

关于rust - 为什么用==比较两个看似相等的指针可以返回false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47489449/

相关文章:

rust - 如何确定可以格式化的字体的打印宽度?

file - 为什么 File::bytes 以不同于 hexdump 的顺序遍历字节?

rust - 编译时检查编译器是否nightly

vector - 在迭代器中找到第一个特定的枚举变体并对其进行转换

rust - 如何查看 TcpStream 并阻塞直到有足够的字节可用?

rust - 为什么 Rust 编译器要求我限制泛型类型参数的生命周期(错误 E0309)?

rust - 如何在 Rust 中获取向量中的最小值?

pattern-matching - 编译器中 AST 结构的模式匹配

rust - Arc 是否允许 RwLock 拥有多个写入器?

rust - 如何在模块内部使用 const?