Are const references guaranteed to point to the same object?

Equal constant references seem to be combined into a single static object. Is this guaranteed?

    const FOO: &[i32; 10] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const BAR: &[i32; 10] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    assert!(std::ptr::eq(FOO, BAR));

How about this?

    const FOO: &[i32; 10] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    assert!(std::ptr::eq(FOO, FOO));

I asked a similar question a few days ago; no they are not, the compiler may "reevaluate" the const anywhere it is used.

https://users.rust-lang.org/t/associated-const-pointer-equality/65220

1 Like

Any const value is like a 0-parameter macro in a way, in that it is expanded at each call site regardless of what happens at other call sites. So unless the expression of the const is something that's guaranteed to point at 1 specific value (e.g. when it's owned by a lazy_static!) it will pretty much point to a new value every time.

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.