Skip to content

Lambdas in unsafe are inlined at every call site #314

Description

@lucic71

The corresponding Rust closure is not saved in a let binding, instead, on every closure call, the body is fully inlined.

template <typename F> int apply(F fn, int x) { return fn(x); }

int main() {
  int base = 10;
  auto add_base = [&base](int x) { return x + base; };
  return apply(add_base, 5);
}

becomes

pub unsafe fn apply_0(mut fn_: impl Fn(i32) -> i32, mut x: i32) -> i32 {
    return fn_(x);
}
unsafe fn main_0() -> i32 {
    let mut base: i32 = 10;
    return apply_0(
        (|x: i32| {
            return x + base;
        })
        .clone(),
        5,
    );
}

A stored closure that captures locals by reference keeps the local borrowed for as long as the closure lives. So let foo = || { a += 1; a }; return foo() + a; does not compile

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions