Skip to content

Can't specialize Drop #46893

Open
Open
@Rantanen

Description

@Rantanen

The Drop trait has checks to ensure that the impl can't add new restrictions on generic parameters.

struct S<T> { ... }
impl<T: Foo> Drop for S<T> { ... }

The above won't compile (as intended?), as the S would have a Drop that's conditional based on the type parameter.

However with specialization we could have something like:

struct S<T> { ... }
default impl<T> Drop for S<T> { ... }
impl <T: Foo> Drop S<T> { ... }

Both of these examples yield the same error

error[E0367]: The requirement `T: Foo` is added only by the Drop impl.

My first instinct was that this had something to do with the type information getting lost on destructors, but that doesn't seem to be the case as the issue can be worked around by specializing a different trait, to which drop delegates to:

struct S<T> { ... }

// Specialized Drop implementation.
trait SpecialDrop { fn drop( &mut self ); }
default impl<T> SpecialDrop for S<T> { ... }
impl<T: Foo> SpecialDrop for S<T> { ... }

// Drop delegates to SpecialDrop.
impl<T> Drop S<T> { fn drop(&mut self) {
    (self as &mut SpecialDrop).drop()
}

Linking to #31844

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-specializationArea: Trait impl specializationC-enhancementCategory: An issue proposing an enhancement or a PR with one.F-specialization`#![feature(specialization)]`T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions