4 ms·
Rust objects can always be moved to arbitrary places in memory, so I'm not sure how "in place" construction of a Rust object can even make sense unless it expli
by zozbot234 6y ago
Rust objects can always be moved to arbitrary places in memory, so I'm not sure how "in place" construction of a Rust object can even make sense unless it explicitly involves the Pin<P> feature to prevent moves. This is quite different from C/C++ where there's no default expectation that a constructed object can be bitwise-copied somewhere else in memory. Even Box<T> is really a special case since the object is meant to be accessed via an owning pointer or a (shared or mutable) reference; when accessing the underlying T by value, that always involves a move of the object so again there's no such thing as being "in place".
- staticassertion 6y agoPlacement 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.