-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Open
Labels
A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)Area: Constant evaluation, covers all const contexts (static, const fn, ...)A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsArea: Lifetimes / regionsC-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: 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.Relevant to the compiler team, which will review and decide on the PR/issue.
Description
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
Labels
A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)Area: Constant evaluation, covers all const contexts (static, const fn, ...)A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsArea: Lifetimes / regionsC-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: 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.Relevant to the compiler team, which will review and decide on the PR/issue.