While reading about the Drop
trait, I found a lot of similarities between the drop
method of Rust and the destructor in a C++. What is the difference between the two?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
In practice, there is no appreciable difference. Both are used to clean up the resources of a type when appropriate.
Resources will be cleaned up irrespective of implementation of the
Drop
trait, won't they?
Yes. The compiler essentially automatically implements Drop
for any type where the programmer does not. This automatic implementation simply calls drop
for each member variable in turn.
If you allocate a resource that Rust doesn't know about, such as allocating memory directly from an allocator, Rust won't know that the returned value needs to be dropped or how to do so. That's when you implement Drop
directly.
See also:
- Running Code on Cleanup with the
Drop
Trait