![](/img/trans.png)
[英]What is the difference between delete and free in C++ and which one is called by the C++'s default destructor?
[英]What is the difference between Rust's Drop and C++'s destructor?
在实践中,没有明显的差异。 两者都用于在适当的时候清理类型的资源。
无论
Drop
trait 的实现如何,资源都会被清理,不是吗?
是的。 编译器本质上会自动为程序员没有实现的任何类型实现Drop
。 这种自动实现只是依次为每个成员变量调用drop
。
如果您分配 Rust 不知道的资源,例如直接从分配器分配内存,Rust 将不知道返回值需要删除或如何删除。 那就是你直接实现Drop
的时候。
也可以看看:
我所知道的唯一区别与 C++ 具有但 Rust 没有的特性有关。 其他人在上面的评论中提到了继承,但一个更简单的例子可能是具有多个构造函数的类型。 在 Rust 中,根据我们所说的“构造函数”,我们可以说每个类型都只有一个构造函数(您命名类型并初始化其所有字段的语法)。 但是在 C++ 中,一个类型可以有多个构造函数,重要的是,一个构造函数可以委托给另一个。 这是一个快速示例:
class foo {
public:
// the inner constructor
foo(bool throw_in_inner_ctor) {
if (throw_in_inner_ctor) {
throw runtime_error("throw in inner ctor");
}
}
// the outer constructor, which delegates to the inner one
foo(bool throw_in_inner_ctor, bool throw_in_outer_ctor)
: foo(throw_in_inner_ctor) {
if (throw_in_outer_ctor) {
throw runtime_error("throw in outer ctor");
}
}
// the destructor
~foo() {
cout << "foo dtor\n";
}
};
int main() {
try {
cout << "construct a foo that throws in its inner ctor\n";
foo(true, false);
} catch (runtime_error) {}
try {
cout << "construct a foo that throws in its outer ctor\n";
foo(false, true);
} catch (runtime_error) {}
}
这打印:
construct a foo that throws in its inner ctor
construct a foo that throws in its outer ctor
foo dtor
我们在这里看到的是,当内部构造函数抛出时,不会调用foo
的析构函数。 但是当外部构造函数抛出时,它会抛出。 规则是,如果任何构造函数无异常返回,我们的foo
将被破坏,而不管其他委托构造函数可能会做什么。 Rust 没有与此规则等效的规则,这既是因为 Rust 没有委托构造函数,也因为 Rust 中的构造函数(如果你想调用它们)不能运行任意代码并且不会失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.