Skip to content

ACP: AtomicPtr::null() to create a null-initialized atomic pointer #715

@orlp

Description

@orlp

Proposal

Problem statement

It's really common to want to null-initialize an atomic pointer. Sometimes AtomicPtr::default() can be used, but not in const contexts. And const contexts are really important specifically for AtomicPtrs, so this is a common constraint.

Motivating examples or use cases

This is an incredibly basic operation so I'll just do a code search for:

So from this primitive research we can establish that around half of the time you actually want to null-initialize an AtomicPtr.

Solution sketch

I propose we add the following method:

impl<T> AtomicPtr<T> {
    pub const fn null() -> Self {
        Self::new(core::ptr::null_mut())
    }
}

With this one can simply write:

static MY_PTR: AtomicPtr<u32> = AtomicPtr::null();

Alternatives

One can simply call AtomicPtr::new(core::ptr::null_mut()). It works but is quite a mouthful.

Another alternative would be to add the associated constant NULL to AtomicPtr. There is precedence for associated constants on generic types (e.g. NonZero::<T>::MAX), but as far as I'm aware not for non-Copy types.

Before trying it and seeing that it does in fact work I personally found it a bit confusing how exactly an associated constant would work for a non-Copy type, so my preference would go out to a const null() constructor.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions