A type without drop will not freed?

Why &Type without drop will be allocated at heap, but having a drop will allocated at stack?

fn mainx() {
    struct Bar {
        i: i32,
        n: i64,
    }

    impl Drop for Bar {
        fn drop(&mut self) {}
    }
    // ERROR
    let cc2: &'static Bar = &Bar { i: 2, n: 0 };
    

    struct Foo {
        i: i32,
        n: i64,
    }
    // OK
    let cc2: &'static Foo = &Foo { i: 2, n: 0 };
}

The non-drop case works because of rvalue static promotion. The value is not allocated on the heap, but rather is stored in the data segment of your binary (along with things like string literals and global static variables).

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.