Skip to content

std::ptr::write docs don't mention that src is leaked #39733

Closed
@niconii

Description

@niconii

EDIT: To summarize it a bit better, since it seems like I worded things a bit unclearly:

src's destructor doesn't get run when it's passed by-value to ptr::write, but the docs don't really make this clear. It would be better to clarify this, especially given it's an unsafe function.


#[derive(Debug)]
struct Foo(i32);

impl Drop for Foo {
    fn drop(&mut self) {
        println!("{:?} dropped!", self);
    }
}

fn main() {
    let mut dst = Foo(0);
    let src = Foo(1);
    
    unsafe { std::ptr::write(&mut dst, src); }
    
    println!("dst = {:?}", dst);
}

This code prints:

dst = Foo(1)
Foo(1) dropped!

demonstrating that the original value stored in dst, and the value passed to std::ptr::write, were not dropped; only dst was dropped after the println! line.

However, the docs for std::ptr::write only mention that the former isn't dropped, saying nothing about the latter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions