You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
A value auto-referenced into a &dyn Trait parameter is moved, not borrowed, and never dropped (§3.9, §3.8) #1881
§3.9 (implicit trait object coercion: a &T passes where &dyn Trait is expected), §3.8 (auto-referencing: peek(x) when peek takes &T), §2.4 (an owned value is dropped once, by its owner).
trait Shape:
fn area(self: &Self) -> i32
type Circle { radius: i32 }
impl Shape for Circle:
fn area(self: &Self) -> i32: self.radius
impl Drop for Circle:
move fn drop(): print(f"drop {self.radius}")
fn peek(s: &dyn Shape): print(f"peek {s.area()}")
fn main:
let a = Circle { radius: 1 }
peek(a)
let b = Circle { radius: 2 }
peek(&b)
print("end")
Prints peek 1, peek 2, end, drop 2. drop 1 never runs: a is neither dropped by main nor by peek. A str-holding implementor leaks its buffer.
Cause
--dump-mir: call sym(peek)(move _1) and no drop(_1); the explicit &b lowers _6 = ref(shared, _4) and drop(_4) at scope exit. Sema's can_auto_ref_arg (SemaCheck.w:335, and the frozen twin at :360) accepts a struct, enum or generic instance whose type equals the pointee; a pointee that is a trait object the actual type implements is refused, so MirLower's lower_auto_ref_call_arg finds no auto-reference and the argument goes by value. Codegen then builds the fat pointer from the moved value's address (the #1847 class: a dyn operand moved where it only borrows).
Found by #1860's view-binding test, whose describe(c) calls never dropped c.
Activity
Sema: a value whose type implements the trait auto-references into a …