1

I am reading rusty_v8's source code.

And I found this code:

  let vtable: &'static RustAllocatorVtable<AtomicUsize> =
    &RustAllocatorVtable {
      allocate,
      allocate_uninitialized,
      free,
      reallocate,
      drop,
    };

https://github.com/denoland/rusty_v8/blob/main/src/array_buffer.rs#L205

I was confused that why &RustAllocatorVtable{} had static lifetime. It allocated on stack and will destroyed after the function scope, isn't it?

abadcafe
  • 61
  • 4
  • 4
    Does this answer your question? [Why can I return a reference to a local literal but not a variable?](https://stackoverflow.com/questions/50345139/why-can-i-return-a-reference-to-a-local-literal-but-not-a-variable) – Chayim Friedman Mar 27 '22 at 20:48
  • 1
    I knew this is a duplicate, but couldn't find it until I posted my answer! :( – Chayim Friedman Mar 27 '22 at 20:48

1 Answers1

3

This is called rvalue static promotion or constant promotion. When the compiler faces a value that can be evaluated at compile-time, it promotes it to a static, like if you wrote:

static S: RustAllocatorVtable<AtomicUsize> = RustAllocatorVtable {
    allocate,
    allocate_uninitialized,
    free,
    reallocate,
    drop,
};
let vtable: &'static RustAllocatorVtable<AtomicUsize> = &S;
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77