]> git.proxmox.com Git - rustc.git/blob - src/doc/nomicon/src/unbounded-lifetimes.md
New upstream version 1.17.0+dfsg1
[rustc.git] / src / doc / nomicon / src / unbounded-lifetimes.md
1 # Unbounded Lifetimes
2
3 Unsafe code can often end up producing references or lifetimes out of thin air.
4 Such lifetimes come into the world as *unbounded*. The most common source of this
5 is dereferencing a raw pointer, which produces a reference with an unbounded lifetime.
6 Such a lifetime becomes as big as context demands. This is in fact more powerful
7 than simply becoming `'static`, because for instance `&'static &'a T`
8 will fail to typecheck, but the unbound lifetime will perfectly mold into
9 `&'a &'a T` as needed. However for most intents and purposes, such an unbounded
10 lifetime can be regarded as `'static`.
11
12 Almost no reference is `'static`, so this is probably wrong. `transmute` and
13 `transmute_copy` are the two other primary offenders. One should endeavor to
14 bound an unbounded lifetime as quickly as possible, especially across function
15 boundaries.
16
17 Given a function, any output lifetimes that don't derive from inputs are
18 unbounded. For instance:
19
20 ```rust,ignore
21 fn get_str<'a>() -> &'a str;
22 ```
23
24 will produce an `&str` with an unbounded lifetime. The easiest way to avoid
25 unbounded lifetimes is to use lifetime elision at the function boundary.
26 If an output lifetime is elided, then it *must* be bounded by an input lifetime.
27 Of course it might be bounded by the *wrong* lifetime, but this will usually
28 just cause a compiler error, rather than allow memory safety to be trivially
29 violated.
30
31 Within a function, bounding lifetimes is more error-prone. The safest and easiest
32 way to bound a lifetime is to return it from a function with a bound lifetime.
33 However if this is unacceptable, the reference can be placed in a location with
34 a specific lifetime. Unfortunately it's impossible to name all lifetimes involved
35 in a function.
36