Is there a C++ equivalent to Rust's `std::mem::drop` in the standard library? -
the function std::mem::drop
in rust moves argument , destroys going out of scope. attempt @ writing similar function in c++ looks 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 function exist in standard library?
edit: function can used invoke destructor of object before going out of scope. consider class closes file handle destroyed, not earlier. sake of argument, suppose ofstream
did not have close
method. can write:
ofstream f("out"); f << "first\n"; drop(move(f)); // f closed now, , flushed disk
c++'s standard library has no such function. however, can accomplish same effect idiom:
sometype var = ...; //do stuff `var`. {auto _ = std::move(var);} //the contents of `var` have been destroyed.
as pointed out in comments, c++ lacks rust's ability prevent further using var
. contents have been moved from, in c++ still live, valid object, , reuse transitioning well-defined state.
of course, requires type move-constructible. types lock_guard
not, you're kinda hosed there. means way close use built-in interface.
Comments
Post a Comment