简体   繁体   English

我可以在 Rust 中就地构建吗?

[英]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我喜欢 C++ 中的 emplace emplace() ing,它可以节省移动构造和破坏:例如strings.push_back("abcd"s)意味着

construct, move, destruct the temporary建造、移动、破坏临时物

while strings.emplace_back("abcd") is just "construct".strings.emplace_back("abcd")只是“构造”。

Can anything similar be achieved in Rust (maybe with compiler optimizations)?可以在 Rust 中实现类似的东西吗(也许通过编译器优化)? The usual vec.push(String::from("abcd")) seems like (in C)通常的vec.push(String::from("abcd"))看起来像(在 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.我认为emplace功能主要由 C++ 中的placement-new功能支持,几年前从 Rust 中删除了类似的不稳定功能。因此,不,不可能用高级代码做类似的事情。

Nevertheless you are still able to use ptr::write and achieve the same behavior in unsafe code.尽管如此,您仍然可以使用ptr::write并在不安全代码中实现相同的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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