From 0c8df59ff60f341ff0cf4d766a7c442b4a5837a4 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 18 Oct 2020 12:04:14 +0200 Subject: [PATCH 1/2] mention how unions interact with dropping --- src/items/unions.md | 10 ++++++++++ src/types/union.md | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/items/unions.md b/src/items/unions.md index 0727b1bd1..d02da57a6 100644 --- a/src/items/unions.md +++ b/src/items/unions.md @@ -79,6 +79,16 @@ u.f1 = 2; Commonly, code using unions will provide safe wrappers around unsafe union field accesses. +## Unions and `Drop` + +When a union is dropped, it cannot know which of its fields needs to be dropped. +For this reason, all union fields must either be of a `Copy` type or of the +shape `ManuallyDrop<_>`. This ensures that a union does not need to drop +anything when it goes out of scope. + +Like for structs and enums, it is possible to `impl Drop` for a union to +manually define what happens when it gets dropped. + ## Pattern matching on unions Another way to access union fields is to use pattern matching. Pattern matching diff --git a/src/types/union.md b/src/types/union.md index b96414fa0..95fe70217 100644 --- a/src/types/union.md +++ b/src/types/union.md @@ -6,7 +6,7 @@ a [`union` item][item]. Unions have no notion of an "active field". Instead, every union access transmutes parts of the content of the union to the type of the accessed field. Since transmutes can cause unexpected or undefined behaviour, `unsafe` is -required to read from a union field or to write to a field that doesn't +required to read from a union field, or to write to a field that doesn't implement [`Copy`]. See the [item] documentation for further details. The memory layout of a `union` is undefined by default, but the `#[repr(...)]` From 0d6f579859c875371c8cfdd6314bb23b19c7a2e8 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 18 Oct 2020 20:36:58 +0200 Subject: [PATCH 2/2] add ManuallyDrop link Co-authored-by: Eric Huss --- src/items/unions.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/items/unions.md b/src/items/unions.md index d02da57a6..7210b0b4c 100644 --- a/src/items/unions.md +++ b/src/items/unions.md @@ -83,7 +83,7 @@ field accesses. When a union is dropped, it cannot know which of its fields needs to be dropped. For this reason, all union fields must either be of a `Copy` type or of the -shape `ManuallyDrop<_>`. This ensures that a union does not need to drop +shape [`ManuallyDrop<_>`]. This ensures that a union does not need to drop anything when it goes out of scope. Like for structs and enums, it is possible to `impl Drop` for a union to @@ -177,3 +177,4 @@ checking, etc etc etc). [_WhereClause_]: generics.md#where-clauses [_StructFields_]: structs.md [`transmute`]: ../../std/mem/fn.transmute.html +[`ManuallyDrop<_>`]: ../../std/mem/struct.ManuallyDrop.html