From 50a974bd4042666f9be806daeeb03188185cbdbd Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Mar 2026 10:07:50 -0700 Subject: [PATCH] Clarify why MaybeUninit::zeroed() is needed. There used to be uncertainty about this topic (is this divergence justified?) but the justification is clear: not zeroing would make it incorrect for Crubit to generate `Default` impls for _many_ translated C++ to Rust types, and performing this check is difficult. On the other hand, zeroing means it's always valid (unless the C++ user *explicitly* does something malicious) and no check is needed. PiperOrigin-RevId: 881493895 --- .../generate_bindings/generate_function.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/rs_bindings_from_cc/generate_bindings/generate_function.rs b/rs_bindings_from_cc/generate_bindings/generate_function.rs index 0167f2239..35914bd66 100644 --- a/rs_bindings_from_cc/generate_bindings/generate_function.rs +++ b/rs_bindings_from_cc/generate_bindings/generate_function.rs @@ -1080,14 +1080,12 @@ fn generate_func_body( .. } | ImplKind::Struct { is_renamed_unpin_constructor: true, .. } => { - // SAFETY: A user-defined constructor is not guaranteed to - // initialize all the fields. To make the `assume_init()` call - // below safe, the memory is zero-initialized first. This is a - // bit safer, because zero-initialized memory represents a valid - // value for the currently supported field types (this may - // change once the bindings generator starts supporting - // reference fields). TODO(b/213243309): Double-check if - // zero-initialization is desirable here. + // SAFETY: Constructors are guaranteed to run all subobject constructors, but primitive + // fields are not necessarily initialized. By zeroing the memory first, we ensure that + // all primitives are initialized to zero. All C++ primitives, when mapped to Rust + // primitives, can accept a zero value (pointers, floats, bools, ints, etc.). One + // notable exception is C++ references, but those cannot be default-initialized, so + // we don't need to worry about them. Ok(quote! { #thunk_prepare let mut tmp = ::core::mem::MaybeUninit::::zeroed();