我想测试两个类型Rc<Trait>
的对象是否包含具体类型的相同实例,因此我将指针与Rc
内的对象进行比较以获得相等性。如果所有代码都驻留在同一个包中,但是当涉及多个包时,它似乎正常工作。
这是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
。但是,当其中一个对象(false
)由另一个包中定义的函数r
返回时,比较将返回Engine::run
。lib.rs
内时,测试正确通过。struct Engine { intval: Object }
来解决问题,但我仍然对为什么感兴趣。答案 0 :(得分:20)
何时是&#34;指针&#34;不是&#34;指针&#34;?当它是胖指针时。 Object
是一个特征,这意味着&Object
是特征对象。特征对象由两个机器指针组成:一个用于具体数据,一个用于 vtable ,一组具体值的特征的具体实现。这个双指针称为胖指针。
使用夜间编译器和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就可以了。
当您使用new
对run
和#[inline]
函数进行注释时,消费者将使用该vtable。
如果你只关心价值的地址,你可以将
as *const _
更改为as *const _ as *const ()
以将胖指针变成常规指针。
可以使用std::ptr::eq
:
use std::ptr;
pub fn is_same(left: &Object, right: &Object) -> bool {
let r = ptr::eq(left, right);
println!("comparing: {:p} == {:p} -> {}", left, right, r);
r
}