Skip to content

Warn when mutably borrowing an unsafe block that returnes a derefenced Copy value #15893

@DHauckCW

Description

@DHauckCW

What it does

Code of the form

let x = &mut unsafe { *y };

where the type of y is Copy successfully compiles, but very likely does not correspond to the intended behaviour.

Advantage

Avoid accidental copying of a value, which leads to the original object being unchanged.

Drawbacks

The code might be written as intended, especially if there are multiple statements inside the unsafe block.

Example

let mut x: u32 = 4; // Somewhere
// ...
let x_ptr: *mut u32 = &raw mut x;
let y = &mut unsafe { *x_ptr };

Could be meant to be written as:

let y = unsafe { &mut *x_ptr };

or

let y = unsafe { x_ptr.as_mut().unwrap() }

or with nightly

let y = unsafe { x_ptr.as_mut_unchecked() }

Comparison with existing lints

No response

Additional Context

The actual behaviour is in my opinion better written as

let y = unsafe { &mut (*x_ptr).clone() };

or

let mut z = unsafe { *x_ptr };
let x = &mut z;

to make the copy more explicit.

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