Skip to content

A value auto-referenced into a &dyn Trait parameter is moved, not borrowed, and never dropped (§3.9, §3.8) #1881

Closed

Description

@ehartford

Spec

§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).

Repro (main at 355c20b and fix-globals alike)

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions