yohhoyの日記

技術的メモをしていきたい日記

オブジェクトのDrop順序

プログラミング言語Rustにおける、オブジェクトデストラクト(Drop)順序についてメモ。[本記事はRust 1.32/Stable準拠]

  • 変数は、その変数宣言順序の逆順。
    • ただし同一パターン内の変数同士では、順序未規定(unspecifined)。
  • 構造体(struct)、タプル、列挙型(enum)のフィールドは、そのフィールド宣言順序の通り。
  • 配列[T; n]Box<[T]>の要素では、インデクス昇順。
    • 可変長配列Vecの要素では、順序未規定(unspecifined)。
  • クロージャにキャプチャされた値は、順序未規定(unspecifined)。

これらのDrop順序を明示的に変更したい場合、std::mem::ManuallyDrop(+unsafeブロック)を用いてデストラクト順を制御することもできる。

The destructor of a type consists of

  • Calling its std::ops::Drop::drop method, if it has one.
  • Recursively running the destructor of all of its fields.
    • The fields of a struct, tuple or enum variant are dropped in declaration order. *
    • The elements of an array or owned slice are dropped from the first element to the last. *
    • The captured values of a closure are dropped in an unspecified order.
    • Trait objects run the destructor of the underlying type.
    • Other types don't result in any further drops.

* This order was stabilized in RFC 1857.


Variables are dropped in reverse order of declaration. Variables declared in the same pattern drop in an unspecified ordered.

https://doc.rust-lang.org/reference/destructors.html

Vec does not currently guarantee the order in which elements are dropped. The order has changed in the past and may change again.

https://doc.rust-lang.org/std/vec/struct.Vec.html

関連URL