Is there equivalent of placement new in rust

Just like the title says. Can I create object in specified memory location (be it safely or unsafely)?

If you already have an initialized value, then provide a mutable reference to it, and dereference it then assign to safely overwrite the existing value.

If you have an uninitialized allocation, you can use ptr::write() for writing a value into an existing allocation without dropping the original (uninitialized) value. This is (obviously) unsafe.

5 Likes

Thanks!

Note that neither of these methods create the value at the desired location. Instead, they create it on the stack and then move it to the place you specify.

In the vast majority of cases, there’s no practical difference between these, but it may cause problems if you’re using unsafe to generate self-references during initialization.

3 Likes

There's no guaranteed placement new. There's some unstable allocator APIs (working group) that cover some of that design space; I haven't tracked that one closely, but I think it has some active design concerns too.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.