Skip to content

Commit b485bf3

Browse files
authored
Merge pull request #15 from rust-rfcs/const_drop
Explain `Drop` in constants
2 parents 752a055 + 67af9f7 commit b485bf3

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

const.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,36 @@ ecosystem that would break if we just started enforcing this now. See
5959
[this issue](https://github.com/rust-lang/rust/issues/49206) and the
6060
[PR attempting to fix this](https://github.com/rust-lang/rust/pull/54424/).
6161

62+
### `Drop`
63+
64+
Values of "needs drop" types
65+
can only be used as the final initialization value of a `const` or `static` item.
66+
They may not be used as intermediate values that would be dropped before the item
67+
were initialized. As an example:
68+
69+
```rust
70+
struct Foo;
71+
72+
impl Drop for Foo {
73+
fn drop(&mut self) {
74+
println!("foo dropped");
75+
}
76+
}
77+
78+
const FOO: Foo = Foo; // Ok, drop is run at each use site in runtime code
79+
static FOOO: Foo = Foo; // Ok, drop is never run
80+
81+
// Not ok, cannot run `Foo::drop` because it's not a const fn
82+
const BAR: i32 = (Foo, 42).1;
83+
```
84+
85+
This restriction might be lifted in the future after trait impls
86+
may be declared `const` (https://github.com/rust-rfcs/const-eval/pull/8).
87+
88+
Note that in promoteds this restriction can never be lifted, because
89+
otherwise we would silently stop calling the `Drop` impl at runtime and
90+
pull it to much earlier (compile-time).
91+
6292
## Reading statics
6393

6494
Beyond values of reference type, we have to be careful that *computing* a

promotion.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,19 @@ compile-time instead of run-time should not alter program behavior.
9797

9898
### 4. Drop
9999

100-
TODO: Fill this with information.
100+
Expressions containing "needs drop" types
101+
can never be promoted. If such an expression were promoted, the `Drop` impl would
102+
never get called on the value, even though the user did not explicitly request such
103+
behavior by using an explicit `const` or `static` item.
104+
105+
As expression promotion is essentially the silent insertion of a `static` item, and
106+
`static` items never have their `Drop` impl called, the `Drop` impl of the promoted
107+
value would never get called.
108+
109+
While it is sound to `std::mem::forget` any value and thus not call its `Drop` impl,
110+
it is unlikely to be the desired behavior in most cases and very likey to be confusing
111+
to the user. If such behavior is desired, the user can still use an explicit `static`
112+
or `const` item and refer to that.
101113

102114
## Open questions
103115

0 commit comments

Comments
 (0)