returning reference to local struct should be denied

Open
#4,941 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 3 days

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
58/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
rust
Domain
compilers

Research direction

Start with the a.rs reproducer in the issue and compare crab1's result with rustc's E0515 diagnostic. Trace the relevant lifetime or borrow-checking entry point, then verify that returning a reference to the local S is rejected without regressing the accepted argument-reference case.

Written by the indexing model from the issue text.

Description

struct S;

fn foo<'a>(x: &'a S) -> &'a S {
    let x = S;
    &x
}

fn main() {}

Here I'm creating S inside the function and then returning an reference to it.
Rustc rejects this:

error[E0515]: cannot return reference to local variable `x`
 --> a.rs:5:5
  |
5 |     &x
  |     ^^ returns a reference to data owned by the current function

warning: unused variable: `x`

crab1 does not error here:

a.rs:1:1: warning: struct is never constructed: ‘S’
    1 | struct S;
      | ^~~~~~
a.rs:3:4: warning: function is never used: ‘foo’
    3 | fn foo<'a>(x: &'a S) -> &'a S {
      |    ^~~
a.rs:3:12: warning: unused name ‘x’ [-Wunused-variable]
    3 | fn foo<'a>(x: &'a S) -> &'a S {
      |            ^

maybe it does not check that the new object actually overwrites the function argument (which would be fine to pass out of the function again via reference)?

crab1 @ 0c3711b3e1a7771032351e99db617e27c719dea

Dominant language
C++
Stars
3k
Forks
238
Avg merge
4d 8h
Merged PRs (30d)
31

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Rust-GCC/gccrs

All issues in Rust-GCC/gccrs

Similar issues

More C++ issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.