简体   繁体   中英

Can I in-place construct in Rust?

I like emplace() ing in C++ which allows to save on move construction and destruction: eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM