我想测试两个类型的对象是否为 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
当两个对象(a
和b
)都在同一个 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]
注释 new
和 run
函数时,使用者将使用该 vtable。
You can change
as *const _
toas *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/