Skip to content

AtomicPtr is invariant in its type parameter #29211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
apasel422 opened this issue Oct 21, 2015 · 2 comments
Closed

AtomicPtr is invariant in its type parameter #29211

apasel422 opened this issue Oct 21, 2015 · 2 comments

Comments

@apasel422
Copy link
Contributor

This differs from the behavior of Box, Arc, Rc, and &.

foo.rs:

use std::sync::atomic::AtomicPtr;

struct Foo<'a>(&'a i32);

fn bar<'a>(x: AtomicPtr<Foo<'static>>) -> AtomicPtr<Foo<'a>> {
    x
}

fn main() {}

Compiler output with rustc 1.5.0-nightly (4826f9625 2015-10-21):

 expected `core::sync::atomic::AtomicPtr<Foo<'a>>`,
    found `core::sync::atomic::AtomicPtr<Foo<'static>>`
(lifetime mismatch) [E0308]
foo.rs:6     x
             ^
foo.rs:6:5: 6:6 help: run `rustc --explain E0308` to see a detailed explanation
foo.rs:5:62: 7:2 note: the lifetime 'a as defined on the block at 5:61...
foo.rs:5 fn bar<'a>(x: AtomicPtr<Foo<'static>>) -> AtomicPtr<Foo<'a>> {
foo.rs:6     x
foo.rs:7 }
note: ...does not necessarily outlive the static lifetime

This stems from the use of UnsafeCell<*mut T> in AtomicPtr's definition instead of UnsafeCell<*const T>.

CC #29037.

@alexcrichton
Copy link
Member

I think though that in this case it's "correct", right? AtomicPtr has interior mutability so if you have AtomicPtr<Foo<'static>> but were able to put a Foo<'a> inside it, that would be bad I think? With Box, Arc, Rc, and & there's no interior mutability which is why I think it's ok to not be invariant.

I could just be saying words here!

@apasel422
Copy link
Contributor Author

It turns out that the use of *mut T doesn't matter, as UnsafeCell itself ensures invariance in order to permit interior mutability, which is basically what @alexcrichton is saying here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants