Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Order of code affects lifetime resolution #23108

Closed
chlai88 opened this issue Mar 6, 2015 · 4 comments
Closed

Order of code affects lifetime resolution #23108

chlai88 opened this issue Mar 6, 2015 · 4 comments

Comments

@chlai88
Copy link

chlai88 commented Mar 6, 2015

This playpen code snippet now fails in compile : playpen

with error

<anon>:23:26: 23:46 error: `long_enough_lifetime` does not live long enough
<anon>:23         handle.set_data(&long_enough_lifetime); // This is OK
                                 ^~~~~~~~~~~~~~~~~~~~
<anon>:17:34: 27:2 note: reference must be valid for the block suffix following statement 0 at 17:33...

But if you just swap the following 2 lines, line 17 with line 18, it compiles fine.

let long_enough_lifetime = DropCanary{label:"long"};
let mut handle = Handle(None);
@Thiez
Copy link
Contributor

Thiez commented Mar 6, 2015

I think this is intended. Because items are destroyed in the opposite order that they are created when they go out of scope, the DropCanary must live strictly longer than the Handle, or otherwise the Handle destructor could see a dropped canary :)

Edit: If you put them on the same line, e.g.:

let (mut handle, long_enough_lifetime) = (Handle(None), DropCanary{label:"long"});

it also works. I'm not sure if this is correct because I'm not aware of the order in which they are dropped in this case.

@pnkfelix
Copy link
Member

pnkfelix commented Mar 6, 2015

This is all by design. See #21657 and rust-lang/rfcs#769

@pnkfelix pnkfelix closed this as completed Mar 6, 2015
@pnkfelix
Copy link
Member

pnkfelix commented Mar 6, 2015

(If we had a way to attach a lifetime to a struct Handle <'a> where the lifetime did not have to outlive the struct value itself, then this code could be made to work. There are not plans currently to add such a feature as of right now, though.)

@pnkfelix
Copy link
Member

pnkfelix commented Mar 6, 2015

Note also that the reason it is okay to put them on the same line is because Handle does not implement Drop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants