The function std::mem::drop
in Rust moves its argument and then destroys it by going out of scope. My attempt at writing a similar function in C++ looks like this:
template <typename T,
typename = std::enable_if_t<std::is_rvalue_reference<T &&>::value>>
void drop(T &&x) {
T(std::move(x));
}
Does such a function already exist in the standard library?
Edit: The function can be used to invoke the destructor of an object before going out of scope. Consider a class that closes a file handle as soon as it is destroyed, but not earlier. For the sake of the argument, suppose ofstream
did not have a close
method. You can write:
ofstream f("out");
f << "first\n";
drop(move(f));
// f is closed now, and everything is flushed to disk
Rust's standard library provides a lot of useful functionality, but assumes support for various features of its host system: threads, networking, heap allocation, and others. There are systems that do not have these features, however, and Rust can work with those too!
The Rust Standard Library is the foundation of portable Rust software, a set of minimal and battle-tested shared abstractions for the broader Rust ecosystem.
The source for Rust's standard library can be obtained by running rustup component add rust-src . It will be downloaded to the <toolchain root>/lib/rustlib/src/rust directory of the current toolchain. The source for the compiler and tools must be obtained from the Rust repository or the standalone source tarballs.
C++'s standard library has no such function. However, you can accomplish the same effect with this idiom:
SomeType var = ...;
//do stuff with `var`.
{auto _ = std::move(var);}
//The contents of `var` have been destroyed.
As pointed out in the comments, C++ lacks Rust's ability to actually prevent you from further using var
. Its contents have been moved from, but in C++ it is still a live, valid object, and you could even reuse it by properly transitioning it to a well-defined state.
Of course, this requires that the type is move-constructible. Some types like lock_guard
are not, so you're kinda hosed there. That means the only way to close it early is to use its built-in interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With