Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a C++ equivalent to Rust's `std::mem::drop` in the standard library?

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
like image 242
Friedrich Avatar asked Jul 27 '17 22:07

Friedrich


People also ask

Does rust have a standard library?

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!

What is rust standard library?

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.

Where is the rust standard library?

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.


1 Answers

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.

like image 136
Nicol Bolas Avatar answered Oct 09 '22 02:10

Nicol Bolas