Skip to content

Suggested lint: avoid &mut to *const coercions #12791

@joshlf

Description

@joshlf

What it does

Recommends avoiding &mut to *const coercions

Advantage

As described in rust-lang/rust#56604, these coercions have surprising behavior that can result in unsoundness in unsafe code. They implicitly first coerce to a shared reference (&), with the result that the resulting raw pointer may have different semantics than a seemingly-equivalent raw pointer produced by first coercing to *mut and then casting to *const. (I say "may" because this depends on how references are formalized in Rust - Stacked Borrows, Tree Borrows, etc.)

Drawbacks

Authors might be relying on this behavior. It strikes me as unlikely to be common - anecdotally, seasoned unsafe programmers I've spoken did not know about this behavior.

Example

let x = &mut 0;
let y: *const i32 = x;

Could be written as:

let x = &mut 0;
let y: *mut i32 = x;
let y = y.cast_const();

cc @RalfJung @jswrenn

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions