Search code examples
c++performancerustin-placeemplace

Can I in-place construct in Rust?


I like emplace()ing in C++ which allows to save on move construction and destruction: e.g. strings.push_back("abcd"s) means

construct, move, destruct the temporary

while strings.emplace_back("abcd") is just "construct".

Can anything similar be achieved in Rust (maybe with compiler optimizations)? The usual vec.push(String::from("abcd")) seems like (in C)

construct + memcpy()

I'm also interested in cases which are more complex than just pushing strings into a vector.


Solution

  • I think emplace feature mostly backed by placement-new feature in C++ and similar unstable feature was removed couple years ago from Rust. Therefore no, it is not possible do the similar with high-level code.

    Nevertheless you are still able to use ptr::write and achieve the same behavior in unsafe code.