Skip to content

UnsafeCell allows types with destructors to end up in statics. #30667

Closed
@eddyb

Description

@eddyb

Apparently this has been used by lazy-static for a while now as a "nightly feature":

use std::cell::UnsafeCell;

struct SyncCell(UnsafeCell<Option<$T>>);
unsafe impl Sync for SyncCell {}

static DATA: SyncCell = SyncCell(UnsafeCell::new(None));

This happens to work even when $T is Vec<X> or String, which should not end up in a static, by the current rules.

A potential fix would involve adding another constant qualification flag for "contains UnsafeCell<D> where D has a destructor" and deny that in a static.
I would like to avoid reusing a combination of the existing flags, as that can result in false positives.

Another possible plan (requiring a new RFC) would be to:

  • allow destructors in statics
    • optionally warn about the "potential leak"
  • allow instantiating structures that impl Drop in constant expressions
  • prevent const items from holding values with destructors, but allow const fn to return them
  • disallow constant expressions which would result in the Drop impl getting called, where they not in a constant context

cc @nikomatsakis @thepowersgang

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-type-systemArea: Type systemC-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions