Summary
Include the ManuallyDrop wrapper in core::mem.
Motivation
Currently Rust does not specify the order in which the destructors are run. Furthermore, this order differs depending on context. RFC issue #744 exposed the fact that the current, but unspecified behaviour is relied onto for code validity and that there’s at least a few instances of such code in the wild.
While a move to stabilise and document the order of destructor evaluation would technically fix the problem described above, there’s another important aspect to consider here – implicitness. Consider such code:
Does this structure depend on Peach’s destructor being run before Banana for correctness?
Perhaps its the other way around and it is Banana’s destructor that has to run first? In the
common case structures do not have any such dependencies between fields, and therefore it is easy
to overlook such a dependency while changing the code above to the snippet below (e.g. so the
fields are sorted by name).
For structures with dependencies between fields it is worthwhile to have ability to explicitly annotate the dependencies somehow.
Detailed design
This RFC proposes adding the following struct as a new lang item to the core::mem (and by extension the std::mem)
module. mem module is a most suitable place for such type, as the module already a place for
functions very similar in purpose: drop and forget.
/// Inhibits compiler from automatically calling `T`’s destructor.
The lang item will be treated specially by the compiler to not emit any drop glue for this type.
Let us apply ManuallyDrop to a somewhat expanded example from the motivation:
It is proposed that this pattern would become idiomatic for structures where fields must be dropped in a particular order.
How We Teach This
It is expected that the functions and wrapper added as a result of this RFC would be seldom necessary.
In addition to the usual API documentation, ManuallyDrop should be mentioned in
reference/nomicon/elsewhere as the solution to the desire of explicit control of the order in which
the structure fields gets dropped.
Alternatives
- Stabilise some sort of drop order and make people to write code that’s hard to figure out at a glance;
- Bikeshed colour;
- Stabilise union and let people implement this themselves:
- Precludes (or makes it much harder) from recommending this pattern as the idiomatic way to implement destructors with dependencies.
Unresolved questions
None known.