3

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.

passing_through
  • 1,778
  • 12
  • 24
  • [The placement by return / guaranteed copy elision RFC discusssion](https://github.com/rust-lang/rfcs/pull/2884) includes discussion of emplacement methods, named `*_with`. – Solomon Ucko Jun 24 '20 at 14:21

1 Answers1

2

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.

Kitsu
  • 3,166
  • 14
  • 28