What is the difference between Rust's Drop and

2019-07-15 03:36发布

问题:

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


标签: c++ rust