Skip to content

Values created by const fns aren't rvalue static promoted #60502

Open
@sfackler

Description

@sfackler

This function compiles due to rvalue static promotion:

fn bar() -> &'static i32 {
    &1
}

This, however, does not:

struct Foo(i32);

impl Foo {
    const fn new(n: i32) -> Foo {
        Foo(n)
    }
}

fn foo() -> &'static Foo {
    &Foo::new(1)
}
error[E0515]: cannot return reference to temporary value
  --> src/lib.rs:10:5
   |
10 |     &Foo::new(1)
   |     ^-----------
   |     ||
   |     |temporary value created here
   |     returns a reference to data owned by the current function

error: aborting due to previous error

Explicitly creating a static does work, however:

struct Foo(i32);

impl Foo {
    const fn new(n: i32) -> Foo {
        Foo(n)
    }
}

fn foo() -> &'static Foo {
    static FOO: Foo = Foo::new(1);
    &FOO
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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