4 ms·
Placement new is just avoiding a copy. Without placement new allocating an object involves: a) Constructing the object on the stack b) Copying it to the heap
by staticassertion 6y ago
Placement new is just avoiding a copy.
Without placement new allocating an object involves:
a) Constructing the object on the stack
b) Copying it to the heap
With placement new you construct the object directly on the heap, thus avoiding a copy.
It's purely an optimization to avoid a single copy. It's a bit surprising that Rust doesn't have it, given the focus on control over such things, and that it had an experimental 'box' keyword for this at 1.0.
edit: To be clear, the extra copy is not guaranteed - compilers can elide it. In order to help the compiler do this you can look at crates like boxext, which provide extension methods on Box that help the compiler to remove the copy. But placement new guarantees this.
- deleted 6y ago[deleted]
- nemothekid 6y agoIIRC, Rust did have this optimization (or LLVM was doing it), but then there was a version bump or change in IR that disabled it and it wasn't trivial to fix.
- staticassertion 6y agoThere should be an optimization pass for this, certainly, but the placement new syntax guarantees it.
- kevincox 6y agoI haven't checked this case but often the compiler will elide the copy. However for cases like this you want it to be very reliable to guaranteed so it would be nice to get that support.