Fri*_*ich 7 c++ destructor lifetime move-semantics rust
std::mem::dropRust中的函数移动其参数,然后通过超出范围来销毁它.我在C++中编写类似函数的尝试如下所示:
template <typename T,
typename = std::enable_if_t<std::is_rvalue_reference<T &&>::value>>
void drop(T &&x) {
T(std::move(x));
}
Run Code Online (Sandbox Code Playgroud)
标准库中是否已存在此类功能?
编辑:该函数可用于在超出范围之前调用对象的析构函数.考虑一个类,它会在文件句柄被销毁后立即关闭,但不会更早.为了论证,假设ofstream没有close方法.你可以写:
ofstream f("out");
f << "first\n";
drop(move(f));
// f is closed now, and everything is flushed to disk
Run Code Online (Sandbox Code Playgroud)
C++的标准库没有这样的功能.但是,你可以用这个成语来达到同样的效果:
SomeType var = ...;
//do stuff with `var`.
{auto _ = std::move(var);}
//The contents of `var` have been destroyed.
Run Code Online (Sandbox Code Playgroud)
正如评论中指出的那样,C++缺乏Rust实际阻止你进一步使用的能力var.它的内容已被移除,但在C++中,它仍然是一个实时有效的对象,您甚至可以通过将其正确转换为明确定义的状态来重用它.
当然,这要求类型是可移动构造的.有些类型不喜欢lock_guard,所以你有点在那里.这意味着早期关闭它的唯一方法是使用其内置接口.